-1

我在我的单元格中添加了 2 个标签并使用 snapkit 设置了这些约束,问题是我无法让单元格正确展开,它保持在默认高度:

titleLabel.snp.makeConstraints { (make) -> Void in
        make.top.equalTo(contentView.snp.top)
        make.bottom.equalTo(descriptionLabel.snp.top)
        make.left.equalTo(contentView.snp.left)
        make.right.equalTo(contentView.snp.right)
    }
    descriptionLabel.snp.makeConstraints { (make) -> Void in
        make.top.equalTo(titleLabel.snp.bottom)
        make.bottom.equalTo(contentView.snp.bottom)
        make.left.equalTo(contentView.snp.left)
        make.right.equalTo(contentView.snp.right)
    }

如您所见,我映射了四个边缘,但是我知道这些并不暗示高度,当内容本质上是动态的并且可能是各种高度时,我该如何应用高度...

标签的设置如下所示:

 lazy var titleLabel: UILabel = {
    let titleLabel = UILabel()
    titleLabel.textColor = .green
    titleLabel.textAlignment = .center
    contentView.addSubview(titleLabel)
    return titleLabel
}()

lazy var descriptionLabel: UILabel = {
    let descriptionLabel = UILabel()
    descriptionLabel.textColor = .dark
    descriptionLabel.textAlignment = .center
    descriptionLabel.numberOfLines = 0
    contentView.addSubview(descriptionLabel)
    return descriptionLabel
}()
4

2 回答 2

1

给表格视图一个estimatedRowHeight,并将其设置rowHeight为 UITableViewAutomaticDimension。现在单元格将自行调整大小。好吧,如果一个标签被所有四个边固定到内容视图,并且如果单元格是自定大小的,那么这就是你所要做的:标签将自动更改其高度以适应其文本,并且单元格将自动更改尺寸以适应标签。

于 2018-02-16T22:40:39.713 回答
0

首先,我认为您应该在子类 UITableViewCell 类初始化方法中向 contentView 添加子视图。

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
           super.init(style: style, reuseIdentifier: reuseIdentifier)
           self.contentView.addSubview(titleLabel)
           self.contentView.addSubview(descriptionLabel)
}

其次,确保在您的 viewDidLoad 方法中(可能在您的 ViewController 中)添加了这两行:

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableView.automaticDimension

当然,您应该更改estimatedRowHeight 以满足您的需要。

还有一件事值得一提——您可以更轻松地创建这些约束(使用 SnapKit 的强大功能):

titleLabel.snp.makeConstraints { (make) -> Void in
    make.top.left.right.equalTo(contentView)
}
descriptionLabel.snp.makeConstraints { (make) -> Void in
    make.top.equalTo(titleLabel.snp.bottom)
    make.bottom.left.right.equalTo(contentView)
}
于 2018-11-23T00:38:42.663 回答