UITableViewCell height not adjusting until user scrolls - ios

I am trying to fill the cell.textLabel with text. That text varies in the number of lines per object in the array, and as such the cell needs to adjust in height. The cell doesn't adjust in height until the user scrolls through the list.
Here in the code.
Image of IB
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:17.0];
cell.textLabel.text = [kanyeLines objectAtIndex:indexPath.row];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText =[kanyeLines objectAtIndex:indexPath.row];
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;
}

So I'd accidentally set the datasource twice for the table instead of setting a delegate.

Related

How to make UITableviewCell (custom) height is depends on the contents?

In my UIViewController I have a UITableView with custom cell.
Please check below image for screenshot.
In that I am giving "multi line " feature to UILabel (The selected label in screenshot) but I have 2 problems now.
When I open this viewcontroller I can see lots of blank space if my UILabel (Description label) have very small text. How can I manage these white spaces?
Please check the app screenshots
My code
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"cell";
InfoCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[InfoCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier];
}
cell.header.text=[names objectAtIndex:indexPath.row];
cell.details.text=[details objectAtIndex:indexPath.row];
[cell.header sizeToFit];
[cell.details sizeToFit];
return cell;
}
Please help to clear these issues
How to make UILabel text size dynamic instead of fixed multiline?
How to make UITableViewCell dynamic depends on its contents height?
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = #“Your text”;
UIFont *cellFont = [UIFont systemFontOfSize:YourFontSize];
CGSize constraintSize = CGSizeMake(TextviewWidth, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
NSLog(#"labelSize : %f", labelSize.height);
return labelSize.height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #“CustomCell”;
CommentCell *cell = (CommentCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSString *cellText = #“LabelText”;
UIFont *cellFont = [UIFont systemFontOfSize:yourFontSize];
CGSize constraintSize = CGSizeMake(LabelWidth, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
cell.lbl.frame = CGRectMake(cell.lbl.frame.origin.x, cell.lbl.frame.origin.y, cell.lbl.frame.size.width, labelSize.height);
cell.lbl.lineBreakMode = NSLineBreakByWordWrapping;
}
This work for me.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strYourText = #"Testing Case ";
NSMutableParagraphStyle *objPS = [[NSMutableParagraphStyle alloc] init];
objPS.lineBreakMode=NSLineBreakByWordWrapping;//here you have to pass the Line break mode which you have to label
CGSize labelSize = CGSizeMake(200.0, 1000.0);///width: label width and set the height 1000.0
CGSize textSizeForLabel = [strYourText boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSParagraphStyleAttributeName : objPS,NSFontAttributeName : [UIFont systemFontOfSize:18.0]} context:nil].size;
float labelHeight =ceilf(textSizeForLabel.height);//this are the only lable height.if there are other UIControls then add their heights and retuns.
//Like if One More Buttons is there in cell then return the button height with dynamic lable height (e.g. return labelHeight+buttonHeight );
//herer we are consider there is a only one label is there so return label height
return labelHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"cell";
InfoCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[InfoCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier];
}
cell.header.numberOfLines = 0;
cell.header.lineBreakMode=NSLineBreakByWordWrapping;
NSString *strYourText = #"Testing Case ";
NSMutableParagraphStyle *objPS = [[NSMutableParagraphStyle alloc] init];
objPS.lineBreakMode=NSLineBreakByWordWrapping;//here you have to pass the Line break mode which you have to label
CGSize labelSize = CGSizeMake(cell.header.frame.size.width, 1000.0);///width label width and set the height 1000.0
CGSize textSizeForLabel = [strYourText boundingRectWithSize:labelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSParagraphStyleAttributeName : objPS,NSFontAttributeName : [UIFont systemFontOfSize:18.0]} context:nil].size;
float labelHeight =ceilf(textSizeForLabel.height);
[cell.header setFrame:CGRectMake(cell.header.frame.origin.x, cell.header.frame.origin.x, cell.header.frame.origin.x, labelHeight)];
cell.header.text=strYourText;
return cell;
}

UILabel height not changing

I am trying to change my two labels heights defined in custom cell but failed many times. Height of labels should change with length of text populated in. I have successfully implemented the cell height in heightForRowAtIndexPAthbut label height is not adjusting according to cell height. It either truncate the text or shrink the font. SetNumberOfLines to zero seems to have no effect. ContentTextView and TransView are my two uiLabels
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Customcell";
CustomeCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSString *text = [_detailItem objectAtIndex:[indexPath row]];
NSString *text2 = [_detailItem2 objectAtIndex:[indexPath row]];
CGSize maxSize = CGSizeMake(296.f, FLT_MAX);
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableAttributedString *attributedString2 = [[NSMutableAttributedString alloc] initWithString:text2];
CGRect rect = [attributedString boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGRect rect2 = [attributedString2 boundingRectWithSize:maxSize
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize maximumLabelSize = CGSizeMake(500,CGFLOAT_MAX);
CGSize requiredSize = [cell.contentTextView sizeThatFits:maximumLabelSize];
CGSize requiredSize2 = [cell.transView sizeThatFits:maximumLabelSize];
CGRect labelFrame = cell.contentTextView.frame;
CGRect labelFrame2 = cell.transView.frame;
labelFrame.size.height = requiredSize.height;
labelFrame2.size.height=requiredSize2.height;
cell.contentTextView.frame = labelFrame;
cell.transView.frame=labelFrame2;
[attributedString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, [text length])];
[attributedString2 addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, [text2 length])];
[cell.contentTextView setLineBreakMode:NSLineBreakByWordWrapping];
[cell.contentTextView setMinimumScaleFactor:FONT_SIZE];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:2];
[style setAlignment:(NSTextAlignment)kCTRightTextAlignment];
[cell.contentTextView setNumberOfLines:0];
[ cell.transView setNumberOfLines:0];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
tableView.separatorColor = [UIColor colorWithRed:0.576 green:0.796 blue:0.008 alpha:1];
cell.contentTextView.attributedText = attributedString;
cell.transView.attributedText=attributedString2;
return cell;
-(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];
UILabel *lblText = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 275, [self dynamicHeightAtIndexPath:indexPath])];
lblText.backgroundColor = [UIColor clearColor];
[lblText setTag:1];
[cell.contentView addSubview:lblText];
}
UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:1];
lbl.numberOfLines=0;
lbl.attributedText = #"label text";
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self dynamicHeightAtIndexPath:indexPath]+20;
}
-(CGFloat)dynamicHeightAtIndexPath:(NSIndexPath *)indexPath
{
CGSize maximumSize = CGSizeMake(275, 9999);
UIFont *myFont =[UIFont fontWithName:#"Halvetica" size:12]; //your font for label
CGSize stringsize = [[self.array objectAtIndex:indexPath.row] sizeWithFont:myFont
constrainedToSize:maximumSize
lineBreakMode:NSLineBreakByWordWrapping];
return stringsize.height;
}
I fixed it by setting constraints on story board. In my case, i had calculate the cell height but my labels height were not adjusting accordingly. I follow the following steps.
1- On story board, click on 'Pin' appeared on bottom and set constraints (click on labels turn by turn).
2- In size inspector, change the intrinsic size of each label to "place holder".
3- Make sure to fix all warnings after you set your constraints otherwise it won't work

Cell size not changing dynamically

I am creating a Iphone app with UITableView. In that I want to change the cell size with respect to text. I used the following code. But it fails.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// CGRect screenBounds = [[UIScreen mainScreen] bounds];
// CGSize screenSize = screenBounds.size;
NSStringDrawingContext *ctx = [NSStringDrawingContext new];
NSAttributedString *aString = [[NSAttributedString alloc] initWithString:[message objectAtIndex:0]];
UITextView *calculationView = [[UITextView alloc] init];
[calculationView setAttributedText:aString];
CGRect textRect = [calculationView.text boundingRectWithSize:self.view.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:calculationView.font} context:ctx];
// CGSize size = [calculationView sizeThatFits:CGSizeMake(screenSize.width, FLT_MAX)];
return textRect.size.height;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
[cell.textLabel setLineBreakMode:NSLineBreakByWordWrapping];
[cell.textLabel sizeToFit];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.imageView.image = [UIImage imageNamed:#"gg.jpg"];
cell.textLabel.text = [NSString stringWithFormat:[message objectAtIndex:0], indexPath.row];
return cell;
}
Thanks in advance.
first you need to get text size.. and according this size you can set cell height.. like this example
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize contsize={260.00f,3000.00f};
UIFont *font=[UIFont fontWithName:#"Open Sans" size:15.0];
NSString *strt11=#"comment_text"
CGSize fontSize=[test sizeWithFont:font constrainedToSize:contsize lineBreakMode:NSLineBreakByWordWrapping];
if (fontSize.height>22)
return fontSize.height+60.0f;
return 80.0f;
}
and also put this code in cellForRowAtIndexPath method for set uilabel height..
Please use the below code.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *text = [array_loaddata objectAtIndex:indexPath.row] ;
UIFont *font = [UIFont systemFontOfSize:10];
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:cellText
attributes:#
{
NSFontAttributeName: cellFont
}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){kWIDTH_FOR_MESSAGE_LABEL, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return rect.size.height + 75;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier =[NSString stringWithFormat:#"Cell%d",indexPath.row] ;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
NSString *text = [array_loaddata objectAtIndex:indexPath.row] ;
UIFont *font = [UIFont systemFontOfSize:10];
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:cellText
attributes:#
{
NSFontAttributeName: cellFont
}];
CGRect rect = [text boundingRectWithSize:(CGSize){kWIDTH_FOR_MESSAGE_LABEL, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(46, 0,kWIDTH_FOR_MESSAGE_LABEL, rect.size.height)];
label.numberOfLines = 0;
label.textColor = [UIColor grayColor];
label.lineBreakMode = NSLineBreakByWordWrapping;
label.text = (text ? text : #"");
label.font = font;
label.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:label];
[label release];
}
As Simple as that :
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}

UITableViewCell wrap text in UINavigationController app

I am having a tableview with different heights for each cell based on the size of the text.
I calculate the rowsize in the delegate method -tableView:heightForRowAtIndexPath, and assign to the text in the datasource method -tableView:cellForRowAtIndexPath.
I am able to realize the appropriate height based on the text, but am not able to make the text wrap around; instead it just disappears off the screen. I am using a navigation-based app to generate the tableview in the child view controller using a nib. I played around with some of the options for tableview, but I can't make the text wrap. I would like to see the next wrap as if it were a textview, but I want the entire content displayed in the cell, without scroll bars in the table cell itself. Is this possible?
Here is the updated code, the height is adjusting itself correctly, but the cell is not word wrapping...
-
(CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *string = [self.quizDictionary objectForKey:[_temp objectAtIndex:testKV]];
CGSize stringSize = [string sizeWithFont:[UIFont boldSystemFontOfSize:15]
constrainedToSize:CGSizeMake(320, 9999)
lineBreakMode:UILineBreakModeWordWrap];
return stringSize.height+25;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int row = indexPath.row;
if (row > 6) {
return nil;
}
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier]
autorelease];
}
// configure the cell...
NSString *string = [self getQuestionPart];
CGSize stringSize = [string sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:UILineBreakModeWordWrap];
UITextView *textV=[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 290, stringSize.height+10)];
textV.font = [UIFont systemFontOfSize:15.0];
textV.text=string;
textV.textColor=[UIColor blackColor];
// textV.editable=NO;
[cell.contentView addSubview:textV];
[textV release];
testKV++;
return cell;
}
You want:
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
to get your text to wrap within the cell. This in combination with a careful implementation of tableView:heightForRowAtIndexPath: should do the trick.
Yes it is possible!!!
Looking at this,you need to be somewhat tricky. You need to calculate the height of the textView dynamically and based on the Height of the TextView,you need to return the Height for the cell..
This is the code by which you can calculate the size of string....
First get the size of String & set the height of the cell based on string
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *d=(NSDictionary *)[self.menuArray objectAtIndex:indexPath.section];
NSString *label = [d valueForKey:#"Description"];
CGSize stringSize = [label sizeWithFont:[UIFont boldSystemFontOfSize:15]
constrainedToSize:CGSizeMake(320, 9999)
lineBreakMode:UILineBreakModeWordWrap];
return stringSize.height+25;
}
- (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];
//}
NSDictionary *d=(NSDictionary *)[self.menuArray objectAtIndex:indexPath.section];
NSString *string = [d valueForKey:#"Description"];
CGSize stringSize = [string sizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:CGSizeMake(320, 9999) lineBreakMode:UILineBreakModeWordWrap];
UITextView *textV=[[UILabel alloc] initWithFrame:CGRectMake(5, 5, 290, stringSize.height+10)];
textV.font = [UIFont systemFontOfSize:15.0];
textV.text=string;
textV.textColor=[UIColor blackColor];
textV.editable=NO;
[cell.contentView addSubview:twitLbl];
[twitLbl release];
return cell;
}

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