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

问题描述 投票:3回答:3

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

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

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

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

A部分

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

也试过了

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }  

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
    }

enter image description here

ios swift uitableview
3个回答
14
投票

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

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

tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension

//委托和数据源

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return UITableViewAutomaticDimension;
}

斯威夫特4:

//委托和数据源

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

Swift 4.2:

//委托和数据源

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

2
投票

在表视图的内容中给出顶部,底部,前导和尾随标签。使用下面的表视图方法

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

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

0
投票
  • 首先设置一个自定义单元格并添加一个标签,并将其行数设置为零,并为单元格的内容视图提供底部,顶部,前导,尾随约束(不要给出高度),同时在viewDidLoad中为单元格大小的单元格提供自定义高度你只需要做,

tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100.0

© www.soinside.com 2019 - 2024. All rights reserved.