This is on iPhone 0S 2.0. Answers for 2.1 are fine too, though I am unaware of any differences regarding tables.
It feels like it should be possible to get text to wrap without creating a custom cell, since a UITableViewCell
contains a UILabel
by default. I know I can make it work if I create a custom cell, but that's not what I'm trying to achieve - I want to understand why my current approach doesn't work.
I've figured out that the label is created on demand (since the cell supports text and image access, so it doesn't create the data view until necessary), so if I do something like this:
cell.text = @""; // create the label
UILabel* label = (UILabel*)[[cell.contentView subviews] objectAtIndex:0];
then I get a valid label, but setting numberOfLines
on that (and lineBreakMode) doesn't work - I still get single line text. There is plenty of height in the UILabel
for the text to display - I'm just returning a large value for the height in heightForRowAtIndexPath
.
I found this to be quite simple and straightForward :
for e.g. :
This may or may not be the best / standard approach to do so, but it worked in my case.
Now the tableviews can have self-sizing cells. Set the table view up as follows
tableView.estimatedRowHeight = 85.0 //use an appropriate estimate tableView.rowHeight = UITableViewAutomaticDimension
Apple Reference
Here is a simpler way, and it works for me:
Inside your
cellForRowAtIndexPath:
function. The first time you create your cell:You'll notice that I set the number of lines for the label to 0. This lets it use as many lines as it needs.
The next part is to specify how large your
UITableViewCell
will be, so do that in yourheightForRowAtIndexPath
function:I added 20 to my returned cell height because I like a little buffer around my text.