在自定义UITableViewCell中调整UILabel大小的问题



我正在尝试创建一个UITableViewCell,里面有许多项目,但我有UILabels的问题。

当使用默认样式UITableViewCell, TextLabelDetailTextLabel只是得到适当的高度适合内容,我只需要使用heightForRowAtIndexPath来计算row height

但是我的自定义cell, UILabelsresize的高度,始终保持size我在界面构建器上设置,我正在尝试这个

    CGRect frame;    
    cell.title.text = item.title;
    frame.origin = cell.title.frame.origin;
    frame.size = [item.title sizeWithFont:[UIFont boldSystemFontOfSize:17]
                       constrainedToSize:CGSizeMake(FB_Cell_width, 4000) lineBreakMode:cell.title.lineBreakMode];
    cell.title.frame = frame;

UILabel的大小不变。

我试一试:

cell.title.text = item.title;
[cell.title sizeToFit];

但尺寸仍然不变。

如何以及在哪里我需要改变UILabel框架,以适应其内容?

编辑:我只是取消使用自动布局选项,现在它似乎工作。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 UILabel *title =  [[UILabel alloc]init]; 
 title.numberOfLines = 0;  
 title.text = item.title;
 float height =  [self heightForText:title.text];
 title.frame = CGRectMake(10, 10, 40, height);
 [cell addSubView:title];
}
- (CGFloat)heightForText:(NSString *)bodyText
{
    UIFont *cellFont = [UIFont systemFontOfSize:30];
    CGSize constraintSize = CGSizeMake(500, MAXFLOAT);
    CGSize labelSize = [bodyText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat height = labelSize.height + 10;
    return height;
}
//try it like this may be it will helps u

使用

cell.title.numberOfLines = 0; //makes your label of unlimited numberoflines
cell.title.text = item.title;
[cell.title sizeToFit];

最新更新