While surfing the web and browsing through development related forums, I encountered a lot of questions regarding multiline UITableViewCells. Prior to iPhone SDK 3.0 this was not an easy feat and although it is very common in UIs, the work that is related to creating multiline cells is not proportional to how common they are.
Apple definitely made it easier with new SDK, since we can interact directly with the UILabel. I know it’s pretty straightforward, but I’m always surprised by how many developers disregard the documentation & turn to forums/blogs for help.
Creating multiline cells is now as simple as setting the numberOfLines property to 0 (or a predefined number) of the textLabel, which is in turn a property of the cell. Given the height of the cell is sufficient, behold a multiline cell.
cell.textLabel.text = @"Some long text..."; cell.textLabel.numberOfLines = 0;
Change the height of the cell with the tableView:heightForRowAtIndexPath: delegate method of the UITableViewController, either by returning a fixed height or by calculating the height needed to show the desired text.
Note that the text property of a cell is being deprecated in favor of textLabel.text, more info on the new 3.0 predefined cell styles can be found here.
Tags: iPhone SDK 3.0, UITableViewCell
Thanks a lot, it’s exactly what I’m looking for.
How can you calculate the height needed to show the desired text?
Have a look at these methods, these allows you to calculate the size of a certain string with a specific font constrained to a specific rectangle.
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
Link to the iPhone developer documentation:
http://developer.apple.com/iphone/library/documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html#//apple_ref/occ/instm/NSString/sizeWithFont:constrainedToSize:lineBreakMode: