简体   繁体   中英

iPhone:How to change rowheight by UILabel's content height

I want to dynamicaly set the cell's rowheight to the UILabel's height (which is cell's subview).

The difficulty is UILabel needs to get its height by checking its string content

Two problems:

1- How can I set correctly the numberofLines in UILabel depending on the string lenght?

2- How can I reflect this UIlabel height to row.height because delegate method heightForRowAtIndexPath is called before the cellForRow method?

here is some code, whcih I am sure I do somethinsg wrong..

Nsstring st= "very long text...";
CGSize theSize = [st sizeWithFont:font constrainedToSize:CGSizeMake(250.0f, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
CGRect cg = CGRectMake(0.0f, 0.0f, 250.0f, theSize.height); 
UILabel *label=[[UILabel alloc] initWithFrame:cg]; 
label.textAlignment=UITextAlignmentLeft;
label.text=st;
[label setNumberOfLines:10];// this is trouble!! how to set this!?
[cell addSubview:label];
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {

CGSize labelSize = CGSizeMake(200.0, 20.0);
if ([string length] > 0)
labelSize = [string sizeWithFont: [UIFont boldSystemFontOfSize: 17.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap];
return 24.0 + labelSize.height;
}

You need to implement heightForRowAtIndexPath. In my sample code, I returned 24 + the height of the label

您可以有一个单独的textForRow:函数,您可以将其用于设置标签的文本,还可以在委托方法中计算标签(和单元格)的大小(就像您已经做过的一样)

(Mashup of my comments)

1- How can I set correctly the numberofLines in UILabel depending on the string lenght?

UILabel 's numberOfLines is the maximum number of lines. "To remove any maximum limit, and use as many lines as needed, set the value of this property to 0."

2- How can I reflect this UIlabel height to row.height because delegate method heightForRowAtIndexPath is called before the cellForRow method?

You need to implement heightForRowAtIndexPath: and return the appropriate height for the row. You can move the computation of theSize to a helper method and use it from cellForRowAtIndexPath: too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM