自动布局UITableViewCells覆盖底部

问题描述 投票:1回答:2

我在使用此UITableViewCell时遇到麻烦。我从服务器获取字符串并将其插入到viewDidLoad中,但是单元格的底部,即summaryLabel被遮盖了。是插图吗? Here's the code

class SummaryTableViewCell: UITableViewCell {
    let titleLabel = UILabel()
    let createdLabel = UILabel()
    let summaryLabel = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        titleLabel.numberOfLines = 2
        titleLabel.lineBreakMode = .byWordWrapping
        titleLabel.font = UIFont.boldSystemFont(ofSize: 23)

        summaryLabel.numberOfLines = 4
        summaryLabel.lineBreakMode = .byWordWrapping

        contentView.clipsToBounds = true
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        createdLabel.translatesAutoresizingMaskIntoConstraints = false
        summaryLabel.translatesAutoresizingMaskIntoConstraints = false

        contentView.addSubview(titleLabel)
        contentView.addSubview(createdLabel)
        contentView.addSubview(summaryLabel)
        let lg = contentView.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            titleLabel.topAnchor.constraint(equalTo: lg.topAnchor),
            titleLabel.leadingAnchor.constraint(equalTo: lg.leadingAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
            titleLabel.bottomAnchor.constraint(equalTo: createdLabel.topAnchor),

            createdLabel.leadingAnchor.constraint(equalTo: lg.leadingAnchor),
            createdLabel.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
            createdLabel.bottomAnchor.constraint(equalTo: summaryLabel.topAnchor, constant: -8),

            summaryLabel.leadingAnchor.constraint(equalTo: lg.leadingAnchor),
            summaryLabel.trailingAnchor.constraint(equalTo: lg.trailingAnchor),
            summaryLabel.bottomAnchor.constraint(equalTo: lg.bottomAnchor)
        ])
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 15, left: 17, bottom: 15, right: 17))
    }
    required init?(coder aDecoder: NSCoder) {super.init(coder: aDecoder)}
}
ios swift uitableview ios-autolayout
2个回答
2
投票

不要将自动布局与通过设置framecontentView表示的帧布局混合,因此用常量替换

titleLabel.topAnchor.constraint(equalTo: lg.topAnchor,constant:15), 
summaryLabel.bottomAnchor.constraint(equalTo: lg.bottomAnchor,constant:-15)

并将所有lbl的前导和尾随更改为这样的东西

titleLabel.leadingAnchor.constraint(equalTo: lg.leadingAnchor,constant:17),
titleLabel.trailingAnchor.constraint(equalTo: lg.trailingAnchor,constant:-17), 

1
投票

另一个选项,可以节省一些精力,并且在您决定执行以下操作时,可以使其更易于调整:

contentView.layoutMargins = UIEdgeInsets(top: 15, left: 17, bottom: 15, right: 17)
let lg = contentView.layoutMarginsGuide

然后,您可以按原样保留约束(无需设置所有常量),并且可以完全删除layoutSubviews()函数。

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