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

时间:2017-03-10 11:21:20

标签: ios objective-c uitableview storyboard 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)

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

我正在使用XCode 8.2.1

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

enter image description here

更新

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

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

}

enter image description here

enter image description here

5 个答案:

答案 0 :(得分:22)

进一步了解道的答案..

他是对的,你需要使用UITableViewAutomaticDimension

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

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

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

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

答案 1 :(得分:11)

使用UITableViewAutomaticDimension

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300

答案 2 :(得分:9)

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

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

第2步:将以下约束赋予UIlabel

  • 对UIImageView的主要约束
  • UIView的最高约束
  • 对UIView的底部约束
  • 向UIView追踪约束

步骤3:然后选择IUlabel的Trailing约束并选择edit选项,然后选择constant并选择greaterThanEqual选项。

第4步:设置标签' s numberofline = 0

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

yourtableview.estimatedRowHeight = 80.0
yourtableview.rowHeight = UITableViewAutomaticDimension

答案 3 :(得分:2)

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

tblView.rowHeight = UITableView.automaticDimension 
tblView.estimatedRowHeight = 300

您还可以通过实现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
      }
    }

答案 4 :(得分:-1)

填充UILabel并应用约束后,获取标签的高度并将其设置为UIView的高度。

之后调用-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath并传递UILabel / UIView的高度,使其获得该行的实际高度

相关问题