自定义 UITableViewCell - 似乎无法添加子视图

Custom UITableViewCell - can't seem to add subview

我创建了一个自定义 UITableViewCell class,如下所示(以编程方式 - 不使用故事板):

import UIKit

class MainGroupCell: UITableViewCell {
    var groupLabel : UILabel {
        let label = UILabel()
        label.textColor = .black
        label.text = "Test Group"
        label.font = UIFont(name: "candara", size: 20)
        return label
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.contentView.addSubview(groupLabel)
        groupLabel.snp.makeConstraints({make in
            make.center.equalTo(self.contentView)
        })
    }

    required init?(coder aDecoder: NSCoder){
        fatalError("init(coder:) has not been implemented")
    }
}

出于某种原因,我遇到了 contentViewgroupLabel 不在同一视图层次结构中的错误,但它们是 - 我已将 groupLabel 添加为如您所见,contentView 的子视图。有什么理由打这个错误吗?我也用常规的 Atuolayout API 试了一下,而不是 SnapKit,但没有这样的运气。感觉这可能是我遗漏的一个小错误。我还尝试了 equalToSuperview 约束,而不是上面显示的约束,但正如预期的那样,它也会引发相同的错误 - groupLabel 的超级视图 returns nil

错误:

Unable to activate constraint with anchors <NSLayoutXAxisAnchor:0x280870b80 
"UILabel:0x105e79fa0'Test Group'.centerX"> and <NSLayoutXAxisAnchor:0x280870a00 
"UITableViewCellContentView:0x105fa16a0.centerX"> because they have no common ancestor. 
 Does the constraint or its anchors reference items in different view hierarchies?  That's illegal.'

试试这个,

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    addSubview(groupLabel)
    groupLabel.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        groupLabel.leadingAnchor.constraint(equalTo: leadingAnchor,constant: 16),
        groupLabel.topAnchor.constraint(equalTo: topAnchor, constant: 16),
        groupLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
        groupLabel.bottomAnchor.constraint(equalTo: bottomAnchor,constant: -16),
    ])

}

像这样更改您的组标签

let groupLabel : UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.text = "Test Group"
        label.font = UIFont(name: "candara", size: 20)
        return label
}()

改为

make.center.equalTo(self.contentView.snp.center)

make.center.equalToSuperview()

而不是

make.center.equalTo(self.contentView)