rpowell
rpowell

Reputation: 1466

Sizing a UITableViewCell based on its contained UITextView

I'm working on an iOS app at the moment where I'm displaying lots of text in table view cells. The text in question is stored in an NSAttributedString can span an indefinite amount of lines and can have inline attachments such as images. The issue here is that I can't seem to get an accurate measure of a given cell's height to pass on to the table view. Is there a performant, simple way to calculate the height of an arbitrarily complex NSAttributedString contained in a UITextView?

Upvotes: 1

Views: 715

Answers (2)

Matt
Matt

Reputation: 2411

I had many failed attempts at this until I came across the free Sensible TableView framework. The framework has what they call a TextViewCell that automatically resizes according to the text inside. Highly recommended.

Upvotes: 1

Wayne Hartman
Wayne Hartman

Reputation: 18477

You can call the boundingRectWithSize:options:context: method to find out its size.

[attributedString boundingRectWithSize:CGSizeMake(320.0f, CGFLOAT_MAX)
                               options:NSStringDrawingUsesLineFragmentOrigin
                               context:nil];

You can substitute the 320.0f with whatever your expected width is for your text view.

Reference: NSAttributedString UIKit Additions Reference

As a footnote, NSString has similar categories outlined here.

Upvotes: 1

Related Questions