Customizing UITableViewCell's height - ios

How can I scale UITableViewCells based on the amount of content in them? In my cells I use 3 labels which represent a forum. The labels are named "alias", "date", and "comments". The third label comments, can be any number of size. Therefore, my cells need to become dynamically depending on how big the "comments" label is. Below is my relevant code:
- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ForumthreadCell";
UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Feedback *item = [self.items objectAtIndex:indexPath.row];
UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1];
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3];
[aliasLabel setText:item.alias];
[commentLabel setText:item.comment];
[dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]];
commentLabel.numberOfLines = 0;
[commentLabel sizeToFit];
CGSize textHeight = [commentLabel.text sizeWithFont:commentLabel.font constrainedToSize:CGSizeMake(maxWidth, lineHeight * commentLabel.numberOfLines)lineBreakMode:UILineBreakModeWordWrap];
return cell;
}
As you can see, I set the height of the commentsLabel with textHeight. But what shall I do from now on? If I know the height of the label, how can I set the Cell's height depending on commentLabel's height?. Please give code-examples based on my code. I think I should use the following method but I am not sure how to do it:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
}

Use this method to get the text height of the text
-(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth
{
CGSize maximumSize = CGSizeMake(labelWidth, 10000);
//provide appropriate font and font size
CGSize labelHeighSize = [text sizeWithFont: [UIFont fontWithName:#"Trebuchet MS" size:13.0f]
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeTailTruncation];
return labelHeighSize.height;
}
This method will return the height of the text you are passing. Add this method in your class. And use the tableView:heightForRowAtIndexPath: delegate method to set the height for each cell
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Feedback *item = [self.items objectAtIndex:indexPath.row];
CGFloat textHeight = [self getLabelHeightForText:item.comment andWidth:162];//give your label width here
return textHeight;
}
I think this could solve the problem.

You could make the Label declarations in your implementation:
#implementation pTableView
{
UILabel *aliasLabel;
}
Then in the row height you could use default Height (44) + aliasLabel.Height
return 44 + aliasLabel.frame.size.height;
Then if you need to differentiate between the labels in your table
aliasLabel.tag = indexpath.row

Related

Cannot change frame of a UILabel in a UITableViewCell when first appearing (using Autolayout)

I have a prototype cell inside my UITableView which contains a UILabel. I want to dynamically change the size of the label (and the cell) depending on the size of the text in the label.
I create the prototype cell in cellForRowAtIndexPath like this:
static NSString *CellIdentifier = #"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
return cell;
Then my ProgramDetailCell has the following implementation:
#implementation ProgramDetailCell
- (void)layoutSubviews {
[super layoutSubviews];
[self.descriptionLabel sizeToFit];
}
#end
The first time the cell is displayed, layoutSubviews is called, but the descriptionLabel does not get resized. However, if I scroll down the table and back up again, the "reused" cell appears with the label correctly resized!
Why does it not work the first time the cell is displayed - and what do I need to do to fix it.
Thanks in advance!
In xib, go to first tab, under Interface Builder Document , uncheck use Auto Layout box.
It doesn't work because you are using auto layout. You need some auto layout way to achieve this.
Here's the solution.
Step 1 :
Have the UILabel Pinned to Top and Bottom of the UITableViewCell. You can achieve this through the Interface Builder by having Vertical Constraint on UILabel from top and bottom of the cell. This will make the UILabel increase in height if the cell's height increase or vice versa.
Step 2:
In your UIViewController in - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath method calculate the size of the UITableViewCell.
You can calculate it using :
CGRect textFrame = [YourText boundingRectWithSize:CGSizeMake(width of the label, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:Your Font} context:nil];
now return the textFrame.size.height + padding if present.
Step 3 :
You will achieve what you wanted --- "dynamically change the size of the label (and the cell) depending on the size of the text in the label" after compiling and running even for the first time.
After retrieving all data from server you can get height of that UILabel using this method.
CGSize maximumSize = CGSizeMake(210, 9999);
for (int i = 0; i < [_arrProductList count]; i++) {
float row_height = 0.0f;
ProductInformation *product_obj = [_arrProductList objectAtIndex:i];
CGSize desc_size = [self measureHeightForText:product_obj.product_desc forFont: [UIFont systemFontOfSize:14] forSize:maximumSize];
row_height = row_height + desc_size.height;
// [_arrRowHeights addObject:[NSString stringWithFormat:#"%f", row_height]]; You can take it into array.
}
[tableView reloadData];
And here i have given description of measureHeightForText:. This logic is working in all iOS5,iOS6,iOS7.
-(CGSize)measureHeightForText:(NSString *)strText forFont:(UIFont *)font forSize:(CGSize)size{
if (!testingLabel) {
testingLabel = [[UILabel alloc] init];
// testingLabel.font = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
testingLabel.text = #"";
testingLabel.numberOfLines = 0;
}
testingLabel.text =strText;
testingLabel.font = font;
CGSize expectedSize = [testingLabel sizeThatFits:size];
return expectedSize;
}
And then update size of your label according it. This is working fine for me. I am using it.
Because when layoutSubviews is called your descriptionLabel's text is not set yet. And when you scroll, the text is set. So it is correct now.
I suggest you call sizeToFit after you set the text.
static NSString *CellIdentifier = #"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
[cell.descriptionLabel sizeToFit];
return cell;
Call this in heightForRowAtIndexPath and manually calculate the height
static NSString *CellIdentifier = #"ProgramDetailCell";
ProgramDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.descriptionLabel.text = self.program.subtitle;
[cell.descriptionLabel sizeToFit];
return cell.descriptionLabel.frame.size.height+cell.descriptionLabel.frame.origin.y;
You can use below code:
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
If your requirement is dynamically changing label height mean follow the below link. When we need to change height of label we need to change the row height also:
Resizing UILabel not quite working
Use below code for dynamic height set in cell
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *messagetext=[NSString stringWithFormat:#"%#",[[arryStoryView objectAtIndex:indexPath.row] valueForKey:#"messagetext"]];
CGSize StoryTextSize= [messagetext sizeWithFont:[UIFont fontWithName:#"Georgia" size:17.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
int TotalHeight;
TotalHeight= StoryTextSize.height + 10;
return TotalHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell1";
UITableViewCell *cell=[tblSendMsg dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString *storytext=[NSString stringWithFormat:#"%#",[[arryStoryView objectAtIndex:indexPath.row] valueForKey:#"storytext"]];
CGSize StoryTextSize = [storytext sizeWithFont:[UIFont fontWithName:#"Georgia" size:17.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
lblStoryText.frame=CGRectMake(5, 25, [[UIScreen mainScreen] bounds].size.width-10, StoryTextSize.height+30);
int nooflines=StoryTextSize.height/16;
int i= StoryTextSize.height;
if(i%16 !=0)
{
nooflines=nooflines+1;
}
lblStoryText.numberOfLines=nooflines;
lblStoryText.font=[UIFont fontWithName:#"Georgia" size:17.0f];
lblStoryText.text=[NSString stringWithFormat:#"%#",storytext];
return cell;
}
If you are using autolayout, modifying the frame will have no effect.
Instead, you should modify the constraints.

UILabel height inside UITableViewCell

I'm trying to create a tableview where the height of the cells are dynamic.
So far I manage to set the height of the cells depending on the custom UILabel I've added inside.
With the regular cell.textLabel it works fine, but when I use my own label something goes wrong. I only see half the label, but when I scroll up and down, sometimes the label extends and shows all the text... You can see where the label should end in the image.
Image
This is the text inside the cellForRowAtIndexPath:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell.
Car *carForCell = [cars objectAtIndex:indexPath.row];
UILabel *nameLabel = [[UILabel alloc] init];
nameLabel = (UILabel *)[cell viewWithTag:100];
nameLabel.numberOfLines = 0;
nameLabel.text = carForCell.directions;
[nameLabel sizeToFit];
[nameLabel setBackgroundColor:[UIColor greenColor]];
return cell;
Unless you have typos in the code you posted, you don't seem to be adding the label to the cell at all. You also seem to be creating a new label every time, and then replacing the contents of your nameLabel pointer with the cell's view (which will always be nil).
Try doing something like this first and then see how it looks:
static NSString *CellIdentifier = #"Cell";
UILabel *nameLabel;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
nameLabel = [[UILabel alloc] init];
nameLabel.tag = 100;
nameLabel.numberOfLines = 0;
[nameLabel setBackgroundColor:[UIColor greenColor]];
[cell.contentView addSubview:nameLabel];
}
else {
nameLabel = (UILabel *)[cell viewWithTag:100];
}
// Configure the cell.
Car *carForCell = [cars objectAtIndex:indexPath.row];
nameLabel.text = carForCell.directions;
[nameLabel sizeToFit];
return cell;
You will also need to tell the tableView what size each cell needs to be using the tableView:heightForRowAtIndexPath: delegate method. That will mean getting the relevant Car object again and calculating the height using sizeWithFont:sizeWithFont:forWidth:lineBreakMode:
How are you setting the height of the cell? It should be done in - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
You should calculate and return the height of the UITableViewCell in the following method:
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
Here you should do your initial calculation of how high your cell should be.
For example:
CGSize textSize = [myString sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(320, 9999)];
return textSize.height;

UITableViewCell's height change after scrolling upwards?

Currently when scrolling upwards in my tableView I have found a strange and annoying bug. When I decide to release the "scroll", meaning I am dropping "the scroll" so the "View" will return to its normal position showing all of the TableView's content, some of my cell's can for some reason re-size themselves on the width. I have no clue why this occur or what the problem might be.
My cell's (commentLabel) are customized to fitSize depending on the height of the label in my forum. I assume the problem may be in how I am trying to customize my cell's content. I will post my relevant code and also post to pictures below.
Before starting to drag the scroll upwards: http://tinypic.com/view.php?pic=2rfsum9&s=6
After release/droped the scroll again to its normal position. Now one of the cell's changed: http://tinypic.com/view.php?pic=swxnqv&s=6
Code:
- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ForumthreadCell";
UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Feedback *item = [self.items objectAtIndex:indexPath.row];
UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1];
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3];
[aliasLabel setText:item.alias];
[commentLabel setText:item.comment];
[dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]];
commentLabel.numberOfLines = 0;
[commentLabel sizeToFit];
return cell;
}
-(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth
{
CGSize maximumSize = CGSizeMake(labelWidth, 10000);
//provide appropriate font and font size
CGSize labelHeighSize = [text sizeWithFont: [UIFont fontWithName:#"Trebuchet MS" size:12.0f]
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeTailTruncation];
return labelHeighSize.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Feedback *item = [self.items objectAtIndex:indexPath.row];
CGFloat commentTextHeight = [self getLabelHeightForText:item.comment andWidth:162];
return commentTextHeight + 39;
}
EDIT
The new code:
CGRect frame = commentLabel.frame;
frame.size.width = kLabelWidth;
frame.size.height = 10000;
commentLabel.frame = frame;
frame = commentLabel.frame;
frame.size.height += kOffset;
commentLabel.frame = frame;
But I have done something wrong since now the text from the commentLabel is not getting displayed correctly, can anyone se my fault here in how I try to set the frame? This is what the cell's look like now http://oi50.tinypic.com/2w5u0s6.jpg
The new full code:
static const CGFloat kLabelWidth = 162;
static const CGFloat kOffset = 39;
- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ForumthreadCell";
UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Feedback *item = [self.items objectAtIndex:indexPath.row];
UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1];
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3];
[aliasLabel setText:item.alias];
[commentLabel setText:item.comment];
[dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]];
CGRect frame = commentLabel.frame;
frame.size.width = kLabelWidth;
frame.size.height = 10000;
commentLabel.frame = frame;
frame = commentLabel.frame;
frame.size.height += kOffset;
commentLabel.frame = frame;
commentLabel.numberOfLines = 0;
[commentLabel sizeToFit];
return cell;
}
You should adjust label frames before reusing cells. In your case you are changing cells height while reusing it in
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
but you should also adjust label's frame according to cell's height so that it will not go beyond cell's bound.

UILabel won't wrap

I'm having a problem with my iOS app and getting a UILabel in a UITableViewCell to wrap. The text shows but it will only display on one line.
Here is my code:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
UILabel *noteLabel = (UILabel *)[cell.contentView viewWithTag:2];
NSDictionary *contact = [jsonResults objectAtIndex:indexPath.row];
noteLabel.lineBreakMode = UILineBreakModeWordWrap;
noteLabel.numberOfLines = 0;
noteLabel.text = [contact objectForKey:#"note"];
return cell;
}
I believe the problem has something to do with this line:
UILabel *noteLabel = (UILabel *)[cell.contentView viewWithTag:2];
I'm not sure how else to get the label from a tag and I think this line won't let me change the labels properties.
You may need to set the label's height:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
UILabel *noteLabel = (UILabel *)[cell.contentView viewWithTag:2];
NSDictionary *contact = [jsonResults objectAtIndex:indexPath.row];
noteLabel.lineBreakMode = UILineBreakModeWordWrap;
noteLabel.numberOfLines = 0;
noteLabel.text = [contact objectForKey:#"note"];
//Note: adjust the proper width to be constrained to
CGSize size = [noteLabel.text sizeWithFont:noteLabel.font forWidth:150 lineBreakMode:noteLabel.lineBreakMode];
CGRect labelFrame = noteLabel.frame;
labelFrame.size = size;
noteLabel.frame = labelFrame;
return cell;
}
Time has moved on since 2012. In the current Xcode 5 world, height is automatically expanded for the multiple lines if numberOfLines is set to 0 in either code or in Interface Builder. One thing that can prevent the multiple lines from being displayed in this scenario is if there is an AutoLayout height constraint set, in Interface Builder or in code. In this scenario, it will look like a label that has been truncated, though in contrast to a truncated label it will not end with an ellipsis (...).
In order for AutoLayout to function as expected, you would not normally want to set a higher height to the UILabel, unless you knew that UILabel would always have multiple lines.
What made the difference for me was setting the label's preferredMaxLayoutWidth.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILabel_Class/#//apple_ref/occ/instp/UILabel/preferredMaxLayoutWidth

How do I wrap text in a UITableViewCell without a custom cell

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.
Here is a simpler way, and it works for me:
Inside your cellForRowAtIndexPath: function. The first time you create your cell:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
}
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 your heightForRowAtIndexPath function:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = #"Go get some text for your cell.";
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 20;
}
I added 20 to my returned cell height because I like a little buffer around my text.
Updated Tim Rupe's answer for iOS7:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = #"Go get some text for your cell.";
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:17.0];
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:cellText
attributes:#
{
NSFontAttributeName: cellFont
}];
CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return rect.size.height + 20;
}
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.
If we are to add only text in UITableView cell, we need only two delegates to work with (no need to add extra UILabels)
1) cellForRowAtIndexPath
2) heightForRowAtIndexPath
This solution worked for me:-
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:16];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
[cell setSelectionStyle:UITableViewCellSelectionStyleGray];
cell.textLabel.text = [mutArr objectAtIndex:indexPath.section];
NSLog(#"%#",cell.textLabel.text);
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png" ]];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize labelSize = CGSizeMake(200.0, 20.0);
NSString *strTemp = [mutArr objectAtIndex:indexPath.section];
if ([strTemp length] > 0)
labelSize = [strTemp sizeWithFont: [UIFont boldSystemFontOfSize: 14.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];
return (labelSize.height + 10);
}
Here the string mutArr is a mutable array from which i am getting my data.
EDIT :- Here is the array which I took.
mutArr= [[NSMutableArray alloc] init];
[mutArr addObject:#"HEMAN"];
[mutArr addObject:#"SUPERMAN"];
[mutArr addObject:#"Is SUPERMAN powerful than HEMAN"];
[mutArr addObject:#"Well, if HEMAN is weaker than SUPERMAN, both are friends and we will never get to know who is more powerful than whom because they will never have a fight among them"];
[mutArr addObject:#"Where are BATMAN and SPIDERMAN"];
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
I use the following solutions.
The data is provided separately in a member:
-(NSString *)getHeaderData:(int)theSection {
...
return rowText;
}
The handling can be easily done in cellForRowAtIndexPath.
Define the cell / define the font and assign these values to the result "cell".
Note that the numberoflines is set to "0", which means take what is needed.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIFont *cellFont = [UIFont fontWithName:#"Verdana" size:12.0];
cell.textLabel.text= [self getRowData:indexPath.section];
cell.textLabel.font = cellFont;
cell.textLabel.numberOfLines=0;
return cell;
}
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.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIFont *cellFont = [UIFont fontWithName:#"Verdana" size:12.0];
CGSize boundingSize = CGSizeMake(1024, CGFLOAT_MAX);
CGSize requiredSize = [[self getRowData:indexPath.section] sizeWithFont:cellFont constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
return requiredSize.height;
}
I found this to be quite simple and straightForward :
[self.tableView setRowHeight:whatEvereight.0f];
for e.g. :
[self.tableView setRowHeight:80.0f];
This may or may not be the best / standard approach to do so, but it worked in my case.
Try my code in swift . This code will work for normal UILabels also.
extension UILabel {
func lblFunction() {
//You can pass here all UILabel properties like Font, colour etc....
numberOfLines = 0
lineBreakMode = .byWordWrapping//If you want word wraping
lineBreakMode = .byCharWrapping//If you want character wraping
}
}
Now call simply like this
cell.textLabel.lblFunction()//Replace your label name
I think this is a better and shorter solution. Just format the UILabel (textLabel) of the cell to auto calculate for the height by specifying sizeToFit and everything should be fine.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = #"Whatever text you want to put here is ok";
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
[cell.textLabel sizeToFit];
return cell;
}
I don't think you can manipulate a base UITableViewCell's private UILabel to do this. You could add a new UILabel to the cell yourself and use numberOfLines with sizeToFit to size it appropriately. Something like:
UILabel* label = [[UILabel alloc] initWithFrame:cell.frame];
label.numberOfLines = <...an appriate number of lines...>
label.text = <...your text...>
[label sizeToFit];
[cell addSubview:label];
[label release];

Resources