我已经使用UITableView
来显示数据库中的项目,我已经创建了自定义的UITableViewCell
,它有几个标签。我最大的标签是name Description。
每个单元格可以有不同的高度,但我不知道如何设置动态单元格的高度。
我得到的只是标签末尾的三个点,单元格的高度总是在50左右。
如何使单元格的高度基于标签里面吗?
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = _orderProperty.Description;
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
constrainedToSize:constraint
lineBreakMode:NSLineBreakByWordWrapping];
CGFloat height = MAX(size.height, 44.0f);
return height + (CELL_CONTENT_MARGIN * 2);
}
static NSString *CellIdentifier = @"orderDetailCell";
OrderDetailCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
[tableView registerNib:[UINib nibWithNibName:@"OrderDetailCustomCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}
OrderProperty* item = [_list objectAtIndex:indexPath.row];
cell.Title.text = item.Title;
NSString* _description = item.Description;
cell.Description.text = _description;
你可以试试这样
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int rowHeight =0.0f;
NSString *stringToSize=[NSString stringWithFormat:@"%@",longStringValue];
CGSize size = [stringToSize
sizeWithFont:[UIFont systemFontOfSize:15.0f]
constrainedToSize:CGSizeMake(300, 6000)
lineBreakMode:NSLineBreakByWordWrapping];
rowHeight = size.height+10;
return rowHeight;
}
你可以从数组中得到longStringValue,你正在使用作为你的表的数据源
您可以在NSString
上使用以下类别,其中使用NSTextContainer
和NSTextContainer
来计算确切的文本大小。
NSString +计算。m
最后的代码是这样的:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = _orderProperty.Description;
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text usedSizeForMaxWidth:constraint.width
withFont:[UIFont systemFontOfSize:FONT_SIZE]];
CGFloat height = MAX(size.height, 44.0f);
return height + (CELL_CONTENT_MARGIN * 2);
}
sizeWithFont现在已弃用,请使用下面的方法根据标签内的文本设置sell的高度。
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
OrderProperty* item = [_list objectAtIndex:indexPath.row];
NSString *text = item.Description;
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont fontWithName:@"Helvetica" size:13] forKey:NSFontAttributeName];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize expectedLabelSize = [content boundingRectWithSize: constraint options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;
return expectedLabelSize.height+CELL_CONTENT_MARGIN * 2);
}
显然,你需要调整字符串属性到你所使用的。这些只是用于计算单元格所需的高度。