我在自动调整单元格高度时遇到问题。单元格中有一个 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 进行自动布局。 UITableViewCell 中的 UILabel 必须全部限制在边缘。我的意思是顶部、底部、前导和尾随约束设置为零或标准值。
有时设置 tableView.estimatedRow
和 tableView.rowHeight
不起作用,所以最好使用委托(delegate)函数:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
关于ios - Swift 4.2 UITableView Cell 不会自动更改其高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972014/