我在单元格中有一个UILabel,我需要动态更改UILabel的高度。因此,单元格是一个xib文件,高度为44,标签为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;
}
但是单元格的高度有时会变小,因此单元格中不会显示文本的所有行。无法理解我做错了什么..有什么帮助吗?
答案 0 :(得分:0)
试试这个,
- (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;
}