字幕单元格的 Swift 自动行高 [英] Swift Automatic Row Height for Subtitle Cell

查看:28
本文介绍了字幕单元格的 Swift 自动行高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UITableView 中使用字幕单元.我在 viewDidLoad 中设置了以下内容以使行高自动扩展:

I am using a subtitle cell in a UITableView. I have set the following in viewDidLoad to make the row height automatically expand:

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 100

我还将单元格的标题和副标题设置为自动换行:

I have also set the title and subtitle of the cell to word wrap:

    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.lineBreakMode = .byWordWrapping

    cell.detailTextLabel?.numberOfLines = 0
    cell.detailTextLabel?.lineBreakMode = .byWordWrapping

当我输入标题时,一切都很好.但是副标题不会扩展该行.我还需要做些什么才能让字幕增加行高?

When I type in the title, all is good. But the subtitle does not expand the row. Is there something else I need to do to get the subtitle to increase the row height?

推荐答案

通过使用来自 https://stackoverflow.com/的代码a/40168001/4045472 并将单元格定义为:

By using this code from https://stackoverflow.com/a/40168001/4045472 and define the cell as:

class MyTableViewCell: UITableViewCell {

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

        self.layoutIfNeeded()
        var size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)

        if let textLabel = self.textLabel, let detailTextLabel = self.detailTextLabel {
            let detailHeight = detailTextLabel.frame.size.height
            if detailTextLabel.frame.origin.x > textLabel.frame.origin.x { // style = Value1 or Value2
                let textHeight = textLabel.frame.size.height
                if (detailHeight > textHeight) {
                    size.height += detailHeight - textHeight
                }
            } else { // style = Subtitle, so always add subtitle height
                size.height += detailHeight
            }
        }

        return size

    }

}

并将storyboard中的单元格自定义类更改为MyTableViewCell会自动设置正确的大小.

And change the cell custom class in storyboard to MyTableViewCell will set the correct size automatically.

在table view数据源的tableView:cellForRow:函数中,设置标签文本后,调用cell.setNeedsLayout()强制调整布局.

In the table view datasource's tableView:cellForRow: function, after set the labels' text, call cell.setNeedsLayout() to force it adjust layout.

这篇关于字幕单元格的 Swift 自动行高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆