I have to solve some problems in existing project (Objective-C, Xcode 7.3, iOS).
Here I have a Table View in which I need to have some resizable cells to fit the content. The cells include Labels. The project uses UITableViewAutomaticDimension but it doesn't seem to work properly. The text in the cell goes beyond the right border.
So now i've checked some points:
The "Lines" property of the cell in Attributes Inspector is set to 0.
I have 4 constraints for the Label (pic related).
The heightForRowAtIndexPath method contains only return UITableViewAutomaticDimension;.
Here is the code, where UITableViewAutomaticDimension is used:
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.estimatedRowHeight = 50.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
Constraints screenshot <======
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 try below one
- (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;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
You need set in IB or in code
[yourLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis: UILayoutConstraintAxisVertical];
[yourLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis: UILayoutConstraintAxisVertical];
And after set the text call this
[cell setNeedsDisplay];
[cell layoutIfNeeded];
Hope this help. I took this from Self Sizing example from Apple
I am Developing an app. I have some data which is coming from server.
Now I Have no Idea about the data count for rows. I only Know the name of Fields.
I want To show these data in UITableViewCell.
I have a custom TableCell. I have taken a ContentView inside it.
I have set the following constraint:
- Leading
- Trailing
- Top
- Bottom
In My ViewController's DidLoad Method I have this Code:
UINib *nib = [UINib nibWithNibName:cellName bundle:nil];
[[self mTableView] registerNib:nib forCellReuseIdentifier:cellName];
self.mTableView.rowHeight = UITableViewAutomaticDimension;
self.mTableView.estimatedRowHeight = 100.0;
I am creating UILabel Like this
- (void)awakeFromNib {
[super awakeFromNib];
CGFloat ypos = 0;
for(int i=0;i<6;i++)
{
UILabel *lbl = [[UILabel alloc]init];
lbl.backgroundColor= [UIColor redColor];
lbl.frame = CGRectMake(0,ypos,30,10);
[self addSubview:lbl];
ypos += 16;
}
[self setNeedsLayout];
[self layoutIfNeeded];
// Initialization code
}
This is my CustomCell.But my TableCell Hegiht is not Increasing.
Please anyone suggest me what is i am missing ?
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
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;
}
You are doing right, so far. But do not forget to use the delegate/data source of your tableView - cellForRowHeight.
Also, as Lion have mentioned, you need to add constraints to your labels. If you do your label programmatically, then do the autolayout programmatically as well.
I would like to create a UILabel that is a little bit wider than the width of the text in the same UILabel. I checked a lot of questions and tried the answers from them, but still can't find the right way. I can get the width of the text, but can't redrawn the frame.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
static NSString *Cell = #"cell";
LikeActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
cell.lbl.backgroundColor = [UIColor colorWithRed:7.0 green:4.0 blue:55.0 alpha:0.7];
NSString *lblString = [NSString stringWithFormat:#"%#", object[#"content"]];
cell.lbl.text = lblString;
float widthIs = [cell.lbl.text
boundingRectWithSize:cell.lbl.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName:cell.lbl.font }
context:nil]
.size.width;
float heightIs =
[cell.lbl.text
boundingRectWithSize:cell.lbl.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName:cell.lbl.font }
context:nil]
.size.height;
NSLog(#"CELL TEXT WIDTH %f", widthIs);
int x = widthIs + 10;
int y = heightIs;
// ATTEMPT 1
[cell.lbl setFrame:CGRectMake(0,0,x,cell.lbl.frame.origin.y)];
// ATTEMPT 2
cell.lbl.frame = CGRectMake(0, 0, x, cell.lbl.frame.origin.y);
return cell;
}
When I run these lines nothing happens, the label doesn't change that I can't understand because it should.
You can have the width of the label wrap around the text with just auto layout. If the text is only one line and you want the label size to fit around that, all you have to do is add a constraint that sets the leading attribute or center X (and constraints for the top/Center Y and height) and make sure you add
[yourLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
[yourLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
after adding it to the subview. If the text is multiline or could be multiline you will need a few more lines of code. You will need to set the compression resistance and hug for the vertical axes,
[yourLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[yourLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
Also add
- (void)layoutSubviews {
if (!CGRectIsEmpty(self.frame)) {
_featureDescriptionLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.contentView.frame)-59-5;
}
[super layoutSubviews];
}
This goes inside your custom table view cell. Set the max layout width to the widest width the text can be inside of your cell.
Also if it is multiline don't forget to set the number of lines to 0.
There is a very good tutorial for calculation of dynamic height of tableView based on its content. Here the UILabel is extended/customized to fit the dynamic content.
http://www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout
Frame setting is not effective because auto layout is on, try to set translatesAutoresizingMaskIntoConstraints property of the label to YES when you set its frame, or you can just turn off auto layout. And
[cell.lbl setFrame:CGRectMake(0,0,x,cell.lbl.frame.origin.y)]; should be
[cell.lbl setFrame:CGRectMake(0,0,x, heightIs)];
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGSize itemTextSize = [#"label text which you want to set" boundingRectWithSize:CGSizeMake(100, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName : [UIFont fontWithName:#"Helvetica Neue" size:12.5]} context:nil].size;
return itemTextSize.height + 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = (UITableViewCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
CGSize itemTextSize = [#"label text which you want to set" boundingRectWithSize:CGSizeMake(100, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName : [UIFont fontWithName:#"Helvetica Neue" size:12.5]} context:nil].size;
itemTextSize.width = itemTextSize.width + 10;
[cell.lbl setFrame:CGRectMake(0, 0, itemTextSize.width, itemTextSize.height)];
return cell;
}
Try below methods for cellForRow and for getting size of your text. Hope this will work for you.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString* cellIdentifier = #"CellIdentifier";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
UILabel *lblComment;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
lblComment=[[UILabel alloc] init];
lblComment.backgroundColor=[UIColor clearColor];
lblComment.font=[UIFont fontWithName:FONT_NAME size:FONT_SIZE];
lblComment.numberOfLines=0;
lblComment.lineBreakMode=NSLineBreakByWordWrapping;
[cell.contentView addSubview:lblComment];
}else{
lblComment=(UILabel *)[[cell.contentView subviews] objectAtIndex:0];
}
lblComment.tag=[self realRowNumberForIndexPath:indexPath inTableView:tableView] + 0;
CGSize Comment_Size = [self GetLAbelSize:lblComment.text LabelFont:FONT_NAME width:FONT_SIZE];
lblComment.frame = CGRectMake(lblComment.frame.origin.x, lblComment.frame.origin.y, Comment_Size.width, Comment_Size.height);
return cell;
}
-(CGSize)GetLAbelSize:(NSString *)str_Text LabelFont:(UIFont *)font width:(float)width
{
CGSize constraintSize = CGSizeMake(width,MAXFLOAT);
// CGSize labelSize = [str_Text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
CGRect boundingRect = [str_Text boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:font} context:nil];
CGSize labelSize = boundingRect.size;
return labelSize;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGSize lblComment = [self GetLAbelHeight:[array_Comment objectAtIndex:indexPath.row] LabelFont:FONT_NAME width:FONT_SIZE];
float totalHeight = lblComment.height+5;
return totalHeight;
}
- (NSInteger)realRowNumberForIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView
{
NSInteger retInt = 0;
if (!indexPath.section)
{
return indexPath.row;
}
for (int i=0; i<indexPath.section;i++)
{
retInt += [tableView numberOfRowsInSection:i];
}
return retInt + indexPath.row;
}
Regards.
Make a custom UITableViewCell. Let's call it CustomCell. Create a XIB, .h and .m for CustomCell. In the XIB, drag a table view cell out so that it is the only thing in the view. Add a label and whatever other views you wish into the cell. Add constraints to the views in whatever way makes sense, and make sure that one of those constraints is a width constraint on the label. Connect this constraint and the label to CustomCell.h. Your CustomCell.h will look like so:
#interface CustomCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelWidth;
#end
Now you can copy/paste the CustomCell from the XIB to the table you want to use the cell in. Then in your cellForRowAtIndexPath:, you can adjust the width of the label as follows, and the other views in the CustomCell will adjust accordingly (thanks, autolayout!).
CGSize size = [self.label sizeThatFits:CGSizeMake(self.frame.size.width, self.frame.size.height)];
self.labelWidth.constant = size.width;
Take a custom UITableViewCell class and setframe in its "layoutSubviews" method
`-(void)layoutSubviews {
[super layoutSubviews];
[self.lbl setFrame:...];
}`
The best way would be to apply proper auto layout constraints for the UILabel.Then if your target is iOS 8 , the set tableview's row height property to UITableViewAutomaticDimension.
or
set a height constraint to the tableview and in viewDidAppear
self.tableViewHeightConstraint.constant = self.tableView.contentSize.height;
in viewWillLayoutSubviews
get tableViewCell object
CGFloat width = label.bounds.size.width;
if ( label.preferredMaxLayoutWidth != width )
{
label.preferredMaxLayoutWidth = width;
[tableViewCell setNeedsLayout];
[tableViewCell layoutIfNeeded];
}
That should do the job if, your auto layout constraints are fine.
Create a fixed width and fixed height constraints on the label (via interface builder), expose them to the view controller (again, via interface builder), and manipulate the layoutconstraints directly:
// in the .h created by interface builder
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelWidth;
#property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelHeight;
...
// in the implementation
[self.labelWidth setConstant:widthIs + 10];
[self.labelHeight setConstant:heightIs];
Assuming you create your custom cell like:
#implementation LikeActivityTableViewCell
-(id)init{
self = [super init];
if(self){
self.lbl = [[UILabel alloc] init];
self.lbl.font = [UIFont fontWithName:#"Arial" size:16]; // Set the font you want
self.lbl.backgroundColor = [UIColor colorWithRed:7.0/255 green:4.0/255 blue:55.0/255 alpha:0.7]; // Dont forget "/255"
[self.contentView addSubview:self.lbl];
}
return self;
}
#end
Then just try:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *Cell = #"cell";
LikeActivityTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:Cell];
if(!cell){
cell = [[LikeActivityTableViewCell alloc] init];
}
cell.lbl.text = [NSString stringWithFormat:#"Am I cell number %d? No!", indexPath.row * 8]; // Put your text here
CGSize labelSize = [self getFrameForLabel:cell.lbl];
labelSize.width += 10.f;
cell.lbl.frame = CGRectMake(cell.contentView.frame.size.width * 0.5f - labelSize.width * 0.5f,
cell.contentView.frame.size.height * 0.5f - labelSize.height * 0.5f,
labelSize.width,
labelSize.height); // I decided to center the label but you can put 0, 0 as origin
return cell;
}
-(CGSize)getFrameForLabel:(UILabel*)label{
NSDictionary *attributes = #{NSFontAttributeName: label.font};
return [label.text sizeWithAttributes:attributes];
}
I managed to do a similar thing using CustomTableViewCell, by setting translatesAutoresizingMaskIntoConstraints of a UILabel property of a custom cell, to true, and then setting the frame of the label to whatever you want by calling customCell.frame = CGRectMake(what, ever, you, want). The only problem with this is that than you will get a warning saying "Unable to simultaneously satisfy constraints.", until you change translatesAutoresizingMaskIntoConstraints to false. This happens when you set your constraints manually through Visual Format. Not sure how to do it through AutoLayout. Im a beginner at this, but thought to share my findings with you anyway, hope it helps a bit. Cheers!
Check if this one helps..
UILabel *type;
type.frame=[self calculateHeightOfTextFromWidth:type withText:type.text];
-(CGRect) calculateHeightOfTextFromWidth:(UILabel*)detailLabel withText:(NSString*)text {
CGRect currentFrame = detailLabel.frame;
CGSize max = CGSizeMake(detailLabel.frame.size.width, 500);
CGSize expected = [text sizeWithFont:detailLabel.font constrainedToSize:max lineBreakMode:detailLabel.lineBreakMode];
currentFrame.size.height = expected.height;
return currentFrame;
}
Here's a method that should return the proper width of your UILabel width based on the height and text string. Set the cell frame with the width returned from this method.
CGFloat *maxWidth = the maximum width you would want your label to be
CGFloat *labelHeight = the height of your label
CGFloat *additionalWidthBuffer = any fixed extra width on your label
-(CGFloat)labelHeightForText:(NSString*) text
{
UIFont * font = [UIFont systemFontOfSize:15.0f];
CGFloat width = [text boundingRectWithSize:CGSizeMake(maxWidth, labelHeight) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:#{NSFontAttributeName: font} context:nil].size.width;
return height + additionalWidthBuffer;
}
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);
}
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;
}