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
.
If we are to add only text in
UITableView
cell, we need only two delegates to work with (no need to add extraUILabels
)1)
cellForRowAtIndexPath
2)
heightForRowAtIndexPath
This solution worked for me:-
Here the string
mutArr
is a mutable array from which i am getting my data.EDIT :- Here is the array which I took.
A brief comment / answer to record my experience when I had the same problem. Despite using the code examples, the table view cell height was adjusting, but the label inside the cell was still not adjusting correctly - solution was that I was loading my cell from a custom NIB file, which happens after the cell height in adjusted.
And I had my settings inside the NIB file to not wrap text, and only have 1 line for the label; the NIB file settings were overriding the settings I adjusted inside the code.
The lesson I took was to make sure to always bear in mind what the state of the objects are at each point in time - they might not have been created yet! ... hth someone down the line.
I use the following solutions.
The data is provided separately in a member:
The handling can be easily done in
cellForRowAtIndexPath
. Define the cell / define the font and assign these values to the result "cell". Note that thenumberoflines
is set to "0", which means take what is needed.In
heightForRowAtIndexPath
, I calculate the heights of the wrapped text. The boding size shall be related to the width of your cell. For iPad this shall be 1024. For iPhone en iPod 320.I think this is a better and shorter solution. Just format the
UILabel
(textLabel
) of the cell to auto calculate for the height by specifyingsizeToFit
and everything should be fine.I don't think you can manipulate a base
UITableViewCell's
privateUILabel
to do this. You could add a newUILabel
to the cell yourself and usenumberOfLines
withsizeToFit
to size it appropriately. Something like:Updated Tim Rupe's answer for iOS7: