Ios Swift 4.2 UITableView单元不';t自动改变它的高度

Ios Swift 4.2 UITableView单元不';t自动改变它的高度,ios,swift,uitableview,uilabel,Ios,Swift,Uitableview,Uilabel,我有一个自动调整单元格高度的问题。单元格中有一个UILabel,它有一个长文本。然而,它是不可见的,因为细胞不会自动变大 import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup afte

我有一个自动调整单元格高度的问题。单元格中有一个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
}

}
结果是:


根据您的代码,我觉得您还没有设置tableView的委托和数据源

tableView.dataSource = self
除此之外,您还需要在viewDidLoad的tableView中注册一个自定义单元格,例如,如下所示:

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

请让我知道它是否有效。

首先,您必须设置tableView的委托和数据源:

tableView.dataSource = self
tableView.delegate = self
完成此操作后,请确保如果您正在使用故事板进行自动布局。UITableViewCell中的UILabel必须约束所有边。我指的是顶部、底部、前导和尾随约束设置为零或标准值

有时设置
tableView.estimatedRow
tableView.rowHeight
不起作用,因此最好使用委托功能:

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

请向我们展示您的标签限制。为了自动调整大小,您应该设置1)委托和数据源。2) 对单元所有边的约束。