UITableViewCell自动调整大小问题Swift

时间:2018-03-23 07:17:55

标签: ios swift storyboard uistoryboard

这是我在UITableViewCell中设计的自定义xib。所选元素是UILabel,需要根据文本量进行扩展。 在故事板单元格中,每个元素都具有恒定的高度和间距。

enter image description here

以下是我在UITableViewController中的代码:

class TableViewController: UITableViewController {
private var exampleContent = ["This is a short text.", "This is another text, and it is a little bit longer.", "Wow, this text is really very very long! I hope it can be read completely! Luckily, we are using automatic row height!, Wow, this text is really very very long! I hope it can be read completely! Luckily, we are using automatic row height!"]

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.delegate = self
    self.tableView.dataSource = self
    tableView.estimatedRowHeight = 224.0
    tableView.rowHeight = UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = Bundle.main.loadNibNamed("DescriptionOnlyCell", owner: self, options: nil)?.first as! DescriptionOnlyCell
    cell.label.numberOfLines = 0
    cell.label.text = exampleContent[indexPath.row]
    return cell
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return exampleContent.count
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

代码的输出与故事板单元格完全相同,没有动态调整大小。

我已经在stackover上阅读了一些线程,其中大多数解释与上面发布的代码相同。虽然我怀疑故事板限制存在一些问题。任何提示都会非常有用。

3 个答案:

答案 0 :(得分:2)

不是为标签设置常量高度值,而是为所有元素设置顶部和底部间距约束,并删除高度约束或将其优先级设置得更低。

答案 1 :(得分:0)

对所选标签执行以下操作:

  
      
  1. 设置行数= 0
  2.   
  3. 设置lineBreak模式= WordWrap
  4.   
  5. 将高度限制设置为> = 15
  6.   

我依赖您分享的信息,设置了所有UI组件的垂直间距。

答案 2 :(得分:0)

我希望这会修复你的大小调整。

    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    tableView.layoutIfNeeded()

}
相关问题