根据内容动态调整tableview单元格的高度 - iOS Swift

use*_*776 6 uitableview ios swift

我试图通过使用部分A中的以下代码,根据详细文本标签中设置的内容动态设置行高.

我将几行文本插入单元格的详细文本标签中,如下面B部分所示

我看过其他类似的问题,但都没有帮助.

有人可以建议我如何根据详细文本标签的内容动态调整行高.

A部分

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)

也试过了

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }  
Run Code Online (Sandbox Code Playgroud)

B部分

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "daysIdentifier", for: indexPath)

        cell.textLabel?.text = days[indexPath.row]

        cell.detailTextLabel?.numberOfLines = 0

        var joinedString            = self.availabilityTimeDict[dayName]?.joined(separator: " \n ")
        cell.detailTextLabel?.text  = joinedString
        return cell
    }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

小智 20

使用自定义单元格和标签.设置UILabel的约束.(上,左,下,右)将UILabel的行设置为0

在ViewController的viewDidLoad方法中添加以下代码:

tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension
Run Code Online (Sandbox Code Playgroud)

//委托和数据源

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension;
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特4:

//委托和数据源

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)