ios - 更改 tableView 单元格内的 UILabel 框架高度

标签 ios objective-c uitableview

我从远程网址获取 UILabel 文本,有时文本太短/太长,我需要调整框架大小以适应文本高度。 我已经使用 xib 实现了服装单元。

screenshot

这是我到目前为止所尝试的,它应该有效,但由于我无法理解的原因而无效:

 cell.fbLastObject.text = [NSString stringWithFormat:@"%@",update.fbLastObject];
 [cell.fbLastObject sizeToFit];

 //Cell Size
 CGSize labelSize = [cell.fbLastObject.text sizeWithFont:cell.fbLastObject.font
                                       constrainedToSize:cell.fbLastObject.frame.size
                                           lineBreakMode:NSLineBreakByWordWrapping];
 labelHeight = labelSize.height;
 cell.fbLastObject.frame = CGRectMake(0,0,300,labelHeight);

有人知道吗?

最佳答案

对于 iOS 8 及更高版本,您可以使用 UITableViewAutomaticDimension 将以下代码放在 viewDidLoad 中:

  tableView.rowHeight = UITableViewAutomaticDimension;
  /* any estimated height but must be more than 2 */
  tableView.estimatedRowHeight = 160.0;
  tableview.delegate = self;
  tableview.dataSource = self;
 // you have created the SimpleTableViewCell.xib, So you need to register that cell with table.
  UINib *nib = [UINib nibWithNibName:@"SimpleTableViewCell" bundle:nil];
  [tableview registerNib:nib forCellReuseIdentifier:@"SimpleTableViewCell"];

现在将适当的 cell fbLastObject 约束(顶部、底部、前导和尾随)引脚添加到 super View 并将行数设置为 0

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"SimpleTableViewCell";

    SimpleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    // here set text for your cell label 
    cell.fbLastObject.text = @"My Text";

    [cell setNeedsLayout];
    [cell layoutIfNeeded];

    return cell;
}

关于ios - 更改 tableView 单元格内的 UILabel 框架高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36012760/

相关文章:

ios - UILabel 在 UITableViewCell 中多次出现

ios - xCode 5.1 无法识别文件系统 "relative to folder"(真实文件夹)中的类

ios - 使用 CIFilter 围绕中心旋转 CIImage

ios - 核心数据未在 TableView 中获取

ios - 仅在 tableview 单元格中制作左下角

objective-c - 从 Objective-C 中的实例十六进制获取类

ios - 如何保存选中的MKAnnotation?

iOS 9 Beta 5 - 日历隐私访问警报未显示在 iPhone 上,但显示在模拟器上

iphone - 打开 iTunes Store 以播放特定歌曲

objective-c - 尝试将文本字段文本设置为字符串时出错