我在单元格中有一个UILabel,我需要动态更改UILabel的高度。因此,单元格是一个高度为 44 的 xib 文件,标签为 240x44,并在水平和垂直方向上自动调整大小。字体为 15.0f 大小,系统。行数 = 0,按单词换行。
所以我有办法
+ (CGFloat) cellHeightForString: (NSString *) string
{
CGFloat cellHeight = [string sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(240.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping].height;
return cellHeight < 44.0f ? 44.0f : cellHeight;
}
但是单元格的高度有时较小,因此并非所有文本行都显示在单元格中。不明白我做错了什么..有什么帮助吗?
试试这个,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// add your code snippet here
// dynamically change the label height,
CGSize textSize = {
200.0, // limit width
20000.0 // and height of text area
};
CGSize contentSize = [yourText sizeWithFont:[UIFont systemFontOfSize:15.0] constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
CGFloat contentHeight = contentSize.height < 36? 36: contentSize.height; // lower bound for height
CGRect labelFrame = [yourLabel frame];
yourLabel.size.height = contentHeight;
[yourLabel setFrame: labelFrame];
[yourLabel setText:yourText];
return cell;
}
动态更改单元格高度,
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
YourCell *currentCell = (YourCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
// change hard coded value based on your cell alignment
int cellLength=[currentCell.yourLabel.text length]/42;
cellLength = cellLength*22 > 200 ? cellLength*22 : 200;
CGSize constraint = CGSizeMake((200 - 10), cellLength);
CGSize size1 = [cellText sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
return 220+size1.height;
}