Swift 4.2 UITableView Cell 不会自动改变高度

Swift 4.2 UITableView Cell doesn't automatically change its height

我在自动调整单元格高度时遇到问题。单元格中有一个 UILabel,它有一个很长的文本。但是,它是不可见的,因为单元格不会自动变大。

import UIKit 
class ViewController: UIViewController {

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    tableView.estimatedRowHeight = 50
    tableView.rowHeight = UITableView.automaticDimension
  }
}

extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CellTableViewCell

    cell.txt.text = "Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. "

    cell.txt.numberOfLines = 0
    cell.txt.lineBreakMode = .byWordWrapping
    cell.txt.sizeToFit()

    return cell
}

}

结果:

<blockquote class="imgur-embed-pub" lang="en" data-id="a/keAv11b"><a href="//imgur.com/keAv11b"></a></blockquote><script async src="//s.imgur.com/min/embed.js" charset="utf-8"></script>

你能检查一下并告诉我哪里出了问题吗?

根据你的代码,在我看来你还没有设置 tableView 的 Delegate 和 DataSource。

tableView.dataSource = self

除此之外,你还需要在viewDidLoad中的tableView中注册一个自定义cell,例如,就这样:

tableView.register(UINib(nibName: "YOUR CELL NAME", bundle: nil), forCellReuseIdentifier: "YOUR CELL REUSE IDENTIFIER")

如果有效请告诉我。

首先你必须设置 tableView 的 Delegate 和 DataSource :

tableView.dataSource = self
tableView.delegate = self

完成后请确保您使用的是 storyBoard for AutoLayout。 UITableViewCell 中的 UILabel 必须全部约束到边缘。我的意思是顶部、底部、前导和尾随约束设置为零或标准值。

有时设置tableView.estimatedRowtableView.rowHeight不起作用所以最好使用委托函数:

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