【问题标题】:Swift 4.2 UITableView Cell doesn't automatically change its heightSwift 4.2 UITableView Cell 不会自动改变它的高度
【发布时间】:2023-03-30 03:04:02
【问题描述】:

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

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

【问题讨论】:

  • 请向我们展示您标签的限制条件。为了使自动调整大小起作用,您应该有 1) 委托和数据源集。 2) 对单元格所有边缘的约束。

标签: ios swift uitableview uilabel


【解决方案1】:

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

tableView.dataSource = self
tableView.delegate = self

这样做之后,请确保如果您正在使用 StoryBoard 进行 AutoLayout。 UITableViewCell 中的 UILabel 必须全部约束到边缘。我的意思是顶部、底部、前导和尾随约束设置为零或标准值。

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

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

【讨论】:

    【解决方案2】:

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

    tableView.dataSource = self
    

    除此之外,还需要在viewDidLoad中的tableView中注册一个自定义单元格,比如这样:

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

    如果有效,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      相关资源
      最近更新 更多