【问题标题】:Expand table view cell height based on it's contents/ [duplicate]根据其内容展开表格视图单元格高度/ [重复]
【发布时间】:2021-07-15 14:49:05
【问题描述】:

我在单元格上有 2 个标签。如果标签只显示一行文本,则单元格看起来不错。但是,如果有更多文本并且标签上的行被包裹起来,那么它上面的标签/文本就会超出单元格。附上图片。

我当前的代码:

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     // Code to dequeue reusable cell.
    
            self.titleLabel.text = "This is a very very long text for the title label. Testing testing"
            self.subTitleLabel.text = "This is a very very long text for the sub title label. Testing testing the wrapping"
            
            self.titleLabel.sizeToFit()
            self.titleLabel.layoutIfNeeded()
            
            self.subTitleLabel.sizeToFit()
            self.subTitleLabel.layoutIfNeeded()
    }

解决方案我尝试修复它:

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     // Code to dequeue reusable cell.

            self.titleLabel.text = "This is a very very long text for the title label. Testing testing"
            self.subTitleLabel.text = "This is a very very long text for the sub title label. Testing testing the wrapping"

            self.titleLabel.sizeToFit()
            self.titleLabel.layoutIfNeeded()

            self.subTitleLabel.sizeToFit()
            self.subTitleLabel.layoutIfNeeded()
    }

override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.estimatedRowHeight = 500
        self.tableView.rowHeight = UITableView.automaticDimension
}

这是解决方案的外观。如何根据内容更新单元格的高度?

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:
  1. 将行数设置为零。 应用适当的约束。

  2. 第二种解决方案 将标签放在stackView中,并将两个标签的行数归零。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多