我有一个自动调整单元格高度的问题。单元格中有一个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
tableView.delegate = self
在这之后,请确保如果您使用storyBoard进行AutoLayout。 UITableViewCell中的UILabel必须全部限制边缘。我的意思是top,bottom,leading和trailing约束设置为零或标准值。
有时设置tableView.estimatedRow
和tableView.rowHeight
不起作用所以最好使用委托功能:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
根据您的代码,在我看来,您还没有设置tableView的Delegate和DataSource。
tableView.dataSource = self
除此之外,您需要在viewDidLoad中的tableView中注册自定义单元格,例如,就像这样:
tableView.register(UINib(nibName: "YOUR CELL NAME", bundle: nil), forCellReuseIdentifier: "YOUR CELL REUSE IDENTIFIER")
如果有效,请告诉我。