UILabel doesn't change height in UITableViewCell in first scroll - ios

I'm using tableview on storyboard.
I change label's frame in (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath function.
then, after some scrolling, it can change frame. but, when I open my application, frame doesn't change at first.
sorry, can't post image till 10 reputation.
please help.
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
// get one row
Plan* planObj = [_planObjList objectAtIndex:indexPath.row];
// get custom cell info
LargeImageCell* cell = (LargeImageCell*)[tableView dequeueReusableCellWithIdentifier:#"CustomLargeImageCell"];
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bg"]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.titleLabel.text = planObj.planTitle;
cell.titleLabel.numberOfLines = 0;
cell.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.userNameLabel.text = planObj.getProducerName;
// title size
CGSize titleSize = [cell.titleLabel.text boundingRectWithSize:CGSizeMake(300.0f, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:#{NSFontAttributeName: cell.titleLabel.font} context:nil].size;
// user name size
CGSize userNameSize = [cell.userNameLabel.text boundingRectWithSize:CGSizeMake(300.0f, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:#{NSFontAttributeName: cell.userNameLabel.font} context:nil].size;
// set title size
cell.titleLabel.frame = CGRectMake(7.0f, 230.0f, 306.0f, ceilf(5.0f + titleSize.height));
cell.titleLabel.backgroundColor = [UIColor redColor];
// set name size
cell.userNameLabel.frame = CGRectMake(7.0f, ceilf(235.0f + titleSize.height), 148.0f, ceilf(5.0f + userNameSize.height));
cell.userNameLabel.backgroundColor = [UIColor blueColor];
}

autolayout was problem.
I switched off 'Use Autolayout' on storyboard. then, it became clear.
thank you all.

If your app is using Autolayout you should do it with Constraints. To resize a UILabel with Constraints that should has at least that properties:
Line Numbers = 0
Line Breaks = Word Wrap
And about Constraints you should set in both sides, and one to top, DONT set to bottom!!
To set right size in the row u can use this code example:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
id data = [self.listOfNews safeObjectAtIndex:indexPath.row];
UIFont *font = [UIFont fontWithName:K_FONT_AVENIR_MEDIUM size:textSize];
if ([data isKindOfClass:[NewsModel class]]) {
NewsModel *news = (NewsModel *)data;
if (SYSTEM_VERSION_LESS_THAN(#"7.0")) {
CGSize constraintSize = CGSizeMake(cellTextWidth, MAXFLOAT);
CGSize textRect = [news.title sizeWithFont:font constrainedToSize:constraintSize];
return textRect.height + paddingTopAndBottom;
} else {
CGRect textRect = [news.title boundingRectWithSize:CGSizeMake(cellTextWidth, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:font}
context:nil];
return textRect.size.height + paddingTopAndBottom;
}
}
return 0;
}

Try resizing frames in willDisplayCell delegate method.

You can't change the size initially through cellForRow method. You need to calculate the size and return it in the following delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
To calculate size for a label based on the text use
NSString *labelText=#"some text";
[myLabel setText:labelText];
UIFont *labelTextFont = [UIFont fontWithName:#"Helvetica" size:labelTextsize];
CGSize labelFrameSize = [labelText sizeWithFont:labelTextFont];
myLabel.frame = CGRectMake(xPos, yPos, labelFrameSize.width, labelFrameSize.height);

Remember these steps in order to have UILabel to change size:
1) If you have a Custom UITableViewCell, switch off AutoLayout on elements of the cell
2) Use heightForRowAtIndex protocol method to change the height
3) Set the numberOfLines = 0 for the UILabel inside the cell
4) If this does not work re-set the frame ( I found that this happens when you are trying to enlarge a UILabel in some "far" end of the cell)
Examples
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
GeneralCell* cell = [tableView dequeueReusableCellWithIdentifier:#"GeneralCell"];
if (cell == nil) {
cell = [[GeneralCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"GeneralCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
/////// USE the following block if still in trouble
CGRect frame = cell.label.frame;
[cell.label setFrame:frame];
[cell.label sizeToFit]; // this should not be necessary in general
///////////
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *detail = [NSString stringWithFormat:#"YOUR TEXT]];
CGSize constraintSize = CGSizeMake(CELL_CONTENT_WIDTH, MAXFLOAT);
CGSize labelSize = [detail boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE]}
context:nil].size;
float h = (fmod((int)labelSize.height ,2) == 0) ? labelSize.height : labelSize.height+1;
CGFloat height = MAX(h, 30.0f);
elemento = nil;
detail = nil;
return height + (CELL_CONTENT_MARGIN * 2);
}

Related

Choppy label on UITableViewCell

I have a functionality where when the user clicks on a cell, the cell expands to display more labels. The height is recalculated during expansion and is based on the size of my very first label or 2nd label on the cell whichever is greater.
Below is my code for height calculation:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize labelSize;
if ([self.expandedCells containsObject:indexPath]) {
// Calculate the cell height based on the address details or branch name which ever is greater.
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:17.0];
BranchDetails *branchDetail = ((BranchDetails *)[self.branchDetails objectAtIndex:[indexPath row]]);
NSString *addressText = branchDetail.addressDetails;
CGSize addressLabelSize = [addressText boundingRectWithSize:CGSizeMake(tableView.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:cellFont} context:nil].size;
NSString *branchNameText = branchDetail.branchName;
CGSize branchLabelSize = [branchNameText boundingRectWithSize:CGSizeMake(tableView.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:cellFont} context:nil].size;
labelSize = (addressLabelSize.height > branchLabelSize.height) ? addressLabelSize : branchLabelSize;
}
else {
NSString *cellText = [self.branchList objectAtIndex:[indexPath row]];
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:17.0];
labelSize = [cellText boundingRectWithSize:CGSizeMake(tableView.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:cellFont} context:nil].size;
}
CGFloat cellHeight = labelSize.height + 20;
return [self.expandedCells containsObject:indexPath] ? cellHeight * 4 : cellHeight;
}
Choppy label cell image:
I tried adding a scroll view while creating a cell in cellForRowAtIndexPath so user can see all the details on the cell. Code for scroll view:
UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];
[cell.contentView addSubview:scrollView];
This still adds the scroll on the table and not within the cell.
Is there a better way for me to either calculate the height, so all the labels within the cell are displayed or add a scroll inside the cell so the user can scroll within each cell after expansion to see all the details?
A better way to do this is to reiterate all UILabels in that cell and then set the height as the sum of all those views heights + gaps.
Something like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGFloat rowHeight = 0;
if ([self.expandedCells containsObject:indexPath]) {
CGFloat totalHeight = 0;
YourCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for(UIView *v in [cell.contentView subviews]) {
if([v isKindOfClass:[UILabel class]]) {
UILabel *lbl = (UILabel*)v;
totalHeight += lbl.frame.size.height;
}
}
rowHeight = totalHeight;
}
else {
rowHeight = 25; // a fixed height for unexpanded rows
}
return rowHeight;
}
This will not work exactly as you want but you can get the idea how to work around it.

Increase the main tableview row height according to the custom cell

I am having an app in which I have a Tableview and on that tableview's each row I am dynamically creating a custom tableview cell.
Below is the code for that.
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"flowviewTableViewCell" owner:self options:nil];
cell2 = [nib objectAtIndex:0];
return cell2;
"FlowTableViewCell" is a UITableViewCell. In this custom cell, I have one tableview.
I am showing some data on my custom tableview cell from an array and those data varies in length. It is not fixed.
I am able to increase the custom cell size but not the main tableview row height depending upon the size of custom tableview cell.
I want to increase the height of the main tableview's cell size dynamically depending upon the size of custom tableview cell.
With the following code, the height of the custom tableView cell is increasing.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = [arrComments objectAtIndex:indexPath.row];
CGSize size = [str sizeWithFont:[UIFont fontWithName:#"Helvetica" size:14] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping];
NSLog(#"%f",size.height);
if (size.height<20)
{
size.height=20;
//m= size.height;
}
NSLog(#"%f",size.height);
return size.height + 30;
}
How can I adjust the height of main tableview's row height depending on the size of custom tableviewcell?
Here,I am attaching some of the screenshots for clear understanding.
The following is my custom TableViewCell:
The following is my main TableView :
Following is the output I am getting right now:
You can see in the above image that comment2 gets cut and comment3 of the same post gets displayed in the next post.
I want output like following Image.
So,my question is how can I increase the height of the main tableview's cell size dynamically depending upon the size of custom tableview cell?
Please help me.any help will be appreciated
You can calculate the Height of Label using:
- (CGRect)heightOfLabel:(UILabel*)resizableLable
{
CGSize constrainedSize = CGSizeMake(resizableLable.frame.size.width , 9999);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"HelveticaNeue" size:11.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:#"textToShow" attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil
];
if (requiredHeight.size.width > self.resizableLable.frame.size.width) {
requiredHeight = CGRectMake(0,0, self.resizableLable.frame.size.width, requiredHeight.size.height);
}
return requiredHeight;
}
Call this method from TableView delegate method:
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
return [self heightOfLabel:cell.textLabel];
}
You can use the following code to adjust the height dynamically. First you need to determine the height of the label and then adjust the height of the cell accordingly. I have been using this code in my chat application and works fine.
First, create the label and image view in cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
/// Set Text Label
UILabel *lbl_myText = [[UILabel alloc]initWithFrame:CGRectZero];
[lbl_myText setLineBreakMode:NSLineBreakByWordWrapping];
lbl_myText.minimumScaleFactor = FONT_SIZE;
[lbl_myText setNumberOfLines:0];
lbl_myText.textAlignment = NSTextAlignmentLeft;
[lbl_myText setFont:[UIFont systemFontOfSize:FONT_SIZE]];
NSString *text = [arr_text objectAtIndex:indexPath.row];
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]];
// Checks if text is multi-line
if (size.width > lbl_myText.bounds.size.width)
{
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f); //// Here Width = Width you want to define for the label in its frame. The height of the label will be adjusted according to this.
//CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
CGRect textRect = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE], NSParagraphStyleAttributeName: paragraphStyle.copy}
context:nil];
CGSize size = textRect.size;
[lbl_myText setText:text];
[lbl_myText setFrame:CGRectMake(cell.imgv_someoneImage.frame.size.width+8, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - cell.imgv_someoneImage.frame.size.width -(CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
}
else
{
lbl_myText.frame = CGRectMake(10, 0, cell.frame.size.width - cell.imgv_someoneImage.frame.size.width - 18,18);
lbl_myText.textAlignment = NSTextAlignmentLeft;
[lbl_myText setText:text];
}
//lbl_myText.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:lbl_myText];
/// Set Date Label
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString *stringFromDate = [formatter stringFromDate:[arr_date objectAtIndex:indexPath.row]];
UILabel *lbl_myDate = [[UILabel alloc]initWithFrame:CGRectMake(cell.imgv_someoneImage.frame.size.width+8, lbl_myText.frame.size.height+10, cell.frame.size.width - cell.imgv_someoneImage.frame.size.width - 10 ,18)];
lbl_myDate.text = stringFromDate;
lbl_myDate.font = [UIFont fontWithName:#"Helvetica Neue" size:13.0];
lbl_myDate.textColor = [UIColor lightGrayColor];
lbl_myDate.textAlignment = NSTextAlignmentLeft;
[cell.contentView addSubview:lbl_myDate];
/// Set User Image
UIImageView *imgv_myImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, lbl_myText.frame.origin.y, 63, 63)];
imgv_myImage.image = selectedUserUploadedImage;
[cell.contentView addSubview:imgv_myImage];
}
Here define some of the constants:
#define FONT_SIZE 15.0f
#define CELL_CONTENT_WIDTH 320.0f /// change this according to your screen size. This is just an example
#define CELL_CONTENT_MARGIN 10.0f
Now, after creating the labels, you will have to determine the height of the cell in heightForRowAtIndexPath:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText = [arr_text objectAtIndex:indexPath.row];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString *cellDate = [formatter stringFromDate:[arr_date objectAtIndex:indexPath.row]];
// NSString *text = [items objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
//CGSize labelsize = [cellText sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
////for message label
CGRect textRect = [cellText boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE], NSParagraphStyleAttributeName: paragraphStyle.copy}
context:nil];
CGSize labelsize = textRect.size;
////for date label
CGRect datetextRect = [cellDate boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE], NSParagraphStyleAttributeName: paragraphStyle.copy}
context:nil];
CGSize datelabelsize = datetextRect.size;
//CGSize datelabelsize = [cellDate sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
///combine the height
CGFloat height = MAX(labelsize.height + datelabelsize.height, 64.0f);
if(height == 64.0f)
{
return 74; /// label is of one line, return original/ static height of the cell
}
else
{
return height + 10; /// label is of multi-line, return calculated height of the cell + some buffer height
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *str = [arrComments objectAtIndex:indexPath.row];
UIFont *font = [UIFont fontWithName:#"Helvetica" size:14];
CGRect new = [str boundingRectWithSize:CGSizeMake(280, 999) options:NSStringDrawingUsesFontLeading attributes:#{NSFontAttributeName: font} context:nil];
CGSize size= new.size;
NSLog(#"%f",size.height);
if (size.height<20)
{
size.height=20;
//m= size.height;
}
NSLog(#"%f",size.height);
return size.height + 30;
}
Here we go:
Create a common UITableViewCell subclass for all the cells in your view (such as FlowViewAbstractTableViewCell)
Create a class method on the table view cell subclass such as + (CGFloat)sizeForCellWithComment:(Comment *)comment. What you're doing is setting up a method to pass a model object into that each table view cell subclass can implement.
Create however many other cell subclasses you need that inherit from FlowViewAbstractTableViewCell. In your case, it looks like you could have ones called FlowViewTextCommentTableViewCell and FlowViewPictureCommentTableViewCell.
For each of those subclasses, implement that +sizeForCellWithComment: method. This will allow you to return a variable size based on the object you pass into the method.
Implement - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath for your UITableViewDelegate. In this method you are going to figure out which cell class you want to use and which object to pass into that size method. For example:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
Comment *commentForCell = [self.comments objectAtIndex:indexPath.row];
return [CommentTableViewCell sizeForComment:commentForCell].height;
}
This will allow you to return a variable cell height based on the object. I use variably sized table view cells all the time & love this pattern because I think it does the best job of hiding the implementation and following MVC.
This video gives a great tutorial on using autolayout to dynamically size UITableViewCells. When I needed to do this for an application I ended up subclassing UITableViewCell and setting my constraints programmatically, and it worked like a charm.
Very simpler solution than the above
Try this
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self.tableName.dataSource tableView:self.tableName cellForRowAtIndexPath:indexPath].contentView.frame.size.height;
}
And in your cellForRowAtIndexPath delegate if you are using label
then first set number of lines to label as 0, then set label text and then add sizeTofit property of it. Like this
[cell.yourLabelName setNumberOfLines:0];
cell.yourLabelName.text = #"Your long or short text";
[cell.yourLabelName sizeToFit];
This will expand your label height as per the text in it.
After that you can set the size of your cell contentView like this.
cell.contentView.frame = CGRectMake(cell.contentView.frame.origin.x, cell.contentView.frame.origin.y, cell.contentView.frame.size.width,"Height of label" + cell.contentView.frame.size.height);

Height issues with UILabel in UITableViewCell

I'm experiencing some trouble with a UILabel in a UITableViewCell that extend its height nicely. But when the cell is reused, and the UILabel text changes, scrolling back up passed labels with correct height when I scrolled down, now is wrong.
As far as I can understand, this is an issue with the UILabel height, but I don't understand what and why it happens.
Heres a video of it happening:
You can see how the labels in the table cells below the images is looking good, but when I scroll back up, they are suddenly only two lines, instead of four.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
InstagramMedia *media = mediaArray[indexPath.section];
CGSize maximumLabelSize = CGSizeMake(304.0f, 20000.0f);
CGSize expectedLabelSize = [media.caption.text sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
return (320.0f + expectedLabelSize.height + 20.0f);
}
Am I missing something here?
I have tried using slightly different approach and it worked in the simulator. Cells kept their height on scrolling.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
InstagramMedia *media = mediaArray[indexPath.section];
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:#"HelveticaNeue" size:12], NSFonatAttributeName, nil];
NSAttributedString *textStr = [[NSAttrebutedString alloc]initWithString:media.caption.text attributes:attributes];
CGSize maximumLabelSize = CGSizeMake(304.0f, 20000.0f);
CGRect expLblRect = [textStr boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
return (320.0f + expLblFrame.size.height + 20.0f);
}
Try this :
- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 186, 0)]; //max width that is allowed for label
lbl.numberOfLines = 0;
lbl.lineBreakMode = NSLineBreakByWordWrapping;
int GAP = 3;
float height = 0;
float fontSize = 14;
NSString *cellText = yourtext;
lbl.font= [ UIFont fontWithName:FONT_NAME_Ubuntu size: fontSize];
bl.text = cellText;
[lbl sizeToFit];
height += lbl.frame.size.height;
height += GAP;
return height;
}
Or you can try this :
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
/*
for dynamic cell heigh according to the description display in cell
*/
NSDictionary *dict1 = (NSDictionary*)[array objectAtIndex:indexPath.row];
NSString *cellText = [dict1 valueForKey:#"test"];
UIFont *cellFont = [UIFont fontWithName:FONT_NAME_GOTHAM_4 size:11.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
return labelSize.height + 80;
}

height For Row At Index Path not correct display

a boy of StackOverflow had given such help to set the height of the cells automatically based on the content of the label ...
I have implemented his method but when I scroll on tavleview, all the text in each cell overlaps and do not read anything ... Can you tell me what 's wrong with this code?
I had to change CGSize because I'm working on some code ios7 was deprecated for example:
 
CGSize size = [comment sizeWithFont: [UIFont systemFontOfSize: 14] constrainedToSize: lineBreakMode constraint: UILineBreakModeWordWrap];
Can you help me please?
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
PFObject *object = [self objectAtIndexPath:indexPath];
//Here you are getting the comment again. This is necessary to determine how tall you need
//the cell to be
NSString *comment = [object objectForKey:(#"Testo")];
// Again you are getting the constraints because you are going to us this size
// to constrain the height of the cell just like you determined the size for the label.
CGSize constraint = CGSizeMake(250 - (10 * 2), 10000.0f);
// Again, determining the size that we will need for the label, because it will drive
// the height of the cell
UIFont *FONT = [UIFont systemFontOfSize:11];
CGSize size = [comment boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:FONT }context:nil].size;
// Finally, we can determine the height for the cell!
CGFloat height = MAX(size.height, 44.0f);
// return the height, which is the height of the label plus some extra space to make
// it look good.
return height + (10 * 2);
}
// Override to customize the look of a cell representing an object. The default is to display
// a UITableViewCellStyleDefault style cell with the label being the first key in the object.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSString *text = [object objectForKey:#"Testo"];
CGSize constraint = CGSizeMake(250 - (10 * 2), 10000.0f);
// This is determining the size that you will need for the label based on the comment
// length and the contraint size
UIFont *FONT = [UIFont systemFontOfSize:11];
CGSize size = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:FONT }context:nil].size;
// Here you are creating your label and initializing it with the frame that you have
// determined by your size calculations above
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, MAX(size.height, 44.0f) + 20.0f)];
// setting up the label properties
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.text = text;
label.font = [UIFont systemFontOfSize:11];
// adding the label view to the cell that you have created
[cell.contentView addSubview:label];
// Configure the cell
return cell;
}
Solved
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *comment = [[self.objects objectAtIndex:[indexPath row]] objectForKey:#"Testo"];
CGFloat whidt = 260;
UIFont *FONT = [UIFont systemFontOfSize:15];
NSAttributedString *attributedText =[[NSAttributedString alloc] initWithString:comment attributes:# { NSFontAttributeName: FONT }];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){whidt, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize size = rect.size;
return size.height +130;
}
- (FFCustomCellTimeline *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
FFCustomCellTimeline *cell = (FFCustomCellTimeline * )[self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (!cell) {
cell = [[FFCustomCellTimeline alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
NSString *text = [object objectForKey:#"Testo"];
CGSize constraint = CGSizeMake(260 , 20000.0f);
UIFont *FONT = [UIFont systemFontOfSize:15];
CGSize size = [text boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:FONT }context:nil].size;
return cell;
}

Setting UITableViewCell height and the cell's text label based on the text height

I have followed the instructions I have been able to find on stackoverflow to fix the following but none have worked. Below is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"DoCCell";
DoCCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[DoCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
CGSize constraintSize = CGSizeMake(cell.infoLabel.frame.size.width, MAXFLOAT);
CGSize labelSize = [_content[[indexPath row] * 2] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:12.0f]
constrainedToSize:constraintSize
lineBreakMode:NSLineBreakByWordWrapping];
CGRect frame = CGRectMake (cell.infoLabel.frame.origin.x, cell.infoLabel.frame.origin.y, labelSize.width, labelSize.height);
[cell.infoLabel setFrame:frame];
cell.infoLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.infoLabel.numberOfLines = 10;
_font = cell.infoLabel.font;
cell.infoLabel.text = _content[[indexPath row] * 2];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize size = [_content[[indexPath row] * 2] sizeWithFont:[UIFont fontWithName:#"HelveticaNeue-Light" size:12.0f]
constrainedToSize:constraintSize
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 30.0;
}
but when I run my code the height of the cells is changed appropriately while the label size is not.
The cell is a custom cell and I have added the label via the .xib file. I tried manually stretching the label which worked in the sense that it would display all of the text so the issue is not in the wrapping of the label. I have also tested the cell.infoLabel.frame.size.height and the height value DOES change with the height of the cell as far as the value is concerned but it is not displayed as such. What am I doing wrong?
I think that the problem might be of adjusting the vertical alignment of the text in the UILabel instance.
I think you should do the following inside cellForRowAtIndexPath:
cell.infoLabel.text = _content[[indexPath row] * 2];
cell.infoLabel.numberOfLines = 0;
[cell.infoLabel sizeToFit];
More details about it can be found in the following link: Vertical Alignment of UILabel Text
Hope this helps! :)
Use below code in cellForRowAtIndexPath delegate of tableView :
// getDynamicHeight function calculates height based on text length
//Dynamically determine height for cell text
CGFloat calculatedHeight = [self getDynamicHeight:#"Some very long text here"];
//Set name label frame based on text height
cell.infoLabel.frame = CGRectMake(cell.infoLabel.frame.origin.x,cell.infoLabel.frame.origin.y, cell.infoLabel.frame.size.width,calculatedHeight);
cell.infoLabel.numberOfLines = 5;
cell.infoLabel.text = #"Some very long text here";
// getDynamicHeight function
//Dynamically determine height for cell based in containing Text
-(CGFloat) getDynamicHeight : (NSString *) strCellTextName {
UILabel *lblGetDynamicHeight = [[UILabel alloc] init];
lblGetDynamicHeight.lineBreakMode = UILineBreakModeWordWrap;
lblGetDynamicHeight.text = strCellTextName;
CGSize labelStringSize = [lblGetDynamicHeight.text sizeWithFont:lblGetDynamicHeight.font constrainedToSize:CGSizeMake(142, 9999) lineBreakMode:lblGetDynamicHeight.lineBreakMode];
return labelStringSize.height; }

Resources