ios - Swift 4.2 UITableView Cell 不会自动更改其高度

标签 ios swift uitableview uilabel

我在自动调整单元格高度时遇到问题。单元格中有一个 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.estimatedRowtableView.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/

相关文章:

ios - 获取当前段落索引

ios - 拍摄应用快照后,当我的 iOS 应用进入后台时,如何节省 subview 中使用的内存

ios - 当应用程序也在后台时从后台线程更新 UI,以便在下一次恢复时显示启动画面

ios - UITableView 加边框也在 HeaderView 上加边框

ios - 使 UITableView 看起来像 iPhone 中的 UIPopover(但没有箭头)

android - COCOS-2d-x : Idea to implement Level progress in games

swift - View Controller 未在 IF 语句中实例化

swift - 我应该如何将文本字段/按钮添加到 TableView Controller ?

ios - 是否可以在单个 TextView 中使用多种字体和大小?

ios - 带有大图像的 UITableViewCell 不流畅