UITableViewCell自动高度基于UILabel文本的数量

Hur*_*rkS 13 objective-c storyboard uitableview ios xcode8

我的故事板中有一个棘手的设置,我有一个UIViewController,它包含一个UITableViewController.在UITableViewController中,我有几个原型单元,我已经链接到代码中的子类uitableviewcell对象.

使用约束和故事板我想根据UILabel最终的大小来改变原型单元格的高度,这取决于进入它的文本.

目前我有一个

UIViewController
-- UITableViewController
-- -- UITableViewCell ((melchat) prototype cell)
-- -- -- ContentView
-- -- -- -- UIView ((background) view with drop shadow card type effect)
-- -- -- -- -- UIImageView (Avatar)
-- -- -- -- -- IUlabel (dynamic (depending on code/input) multi line UILabel)
Run Code Online (Sandbox Code Playgroud)

有些我希望UILabel调整UIView(背景)的大小然后反过来影响UITableViewCell的高度.

我正在使用XCode 8.2.1

我在故事板中采用了布局的屏幕截图并应用了约束.

在此输入图像描述

更新

我已经更新了我的约束,几乎所有回到ContentView并将uilabel行数更新为0,然后还实现了UITableViewAutomaticDimension代码,但它仍然无效.请参阅下面的代码和屏幕截图.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;

}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述

Scr*_*ble 24

再谈Dao的答案..

他是对的,你需要使用 UITableViewAutomaticDimension

此外,您需要确保以一种方式设置约束,即单元格中的所有内容都被约束到单元格contentView.所以你的标签可能需要诸如此类的限制

  • 对ImageView的主要约束
  • 对contentView的最高约束
  • 对contentView的底部约束
  • 跟踪contentView的约束

确保将UILabel设置为多行(或行= 0),它应该可以工作.

如果您使用的是heightForRowAt委托函数,请确保返回 UITableViewAutomaticDimension


Đào*_*Hạt 13

使用 UITableViewAutomaticDimension

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
Run Code Online (Sandbox Code Playgroud)


Bri*_*oya 9

步骤1:将以下约束赋予contentView内部的UIView.

  • 对contentView的主要约束
  • 对contentView的最高约束
  • 对contentView的底部约束
  • 跟踪contentView的约束

第2步:给UIlabel提供以下约束

  • 对UIImageView的主要约束
  • 对UIView的最高约束
  • 对UIView的底限制
  • 跟踪UIView的约束

step3:然后选择IUlabel的Trailing约束并选择edit选项,然后选择constant并选择greaterThanEqual选项.

step4:设置标签 numberofline = 0

第5步:将此代码添加到 viewDidLoad()

yourtableview.estimatedRowHeight = 80.0
yourtableview.rowHeight = UITableViewAutomaticDimension
Run Code Online (Sandbox Code Playgroud)


Gur*_*ngh 5

Swift 4.2和5。如上所述,您可以设置UITableView对象属性或

tblView.rowHeight = UITableView.automaticDimension 
tblView.estimatedRowHeight = 300
Run Code Online (Sandbox Code Playgroud)

您还可以通过实现UITableViewDelegate方法来定义它们

extension ViewController: UITableViewDelegate {
      func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 300
      }
      func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
      }
    }
Run Code Online (Sandbox Code Playgroud)