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

时间:2017-02-25 07:53:55

标签: ios swift uitableview

我正在尝试根据详细文本标签中设置的内容动态设置行高,方法是使用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

3 个答案:

答案 0 :(得分:14)

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

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

tableView.estimatedRowHeight = 68.0
tableView.rowHeight = UITableViewAutomaticDimension

//代表&数据来源

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

Swift 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
}

答案 1 :(得分:2)

将topview,bottom,leading和trailing给tableview的内部内容。使用下面的表格视图方法

@SpringUI
public class SampleUi extends UI {

    @Inject
    private SpringNavigator navigator;

    @Override
    protected void init(VaadinRequest request) {
        navigator.init(this, this); // Explicit init() call
        navigator.navigateTo(StartView.NAME);
    }
}

答案 2 :(得分:0)

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

tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100.0

相关问题