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

时间:2020-04-26 12:50:25

标签: ios swift uitableview snapkit

我已经创建了一个自定义UITableViewCell类,如下所示(以编程方式-对此不使用情节提要):

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的超级视图将返回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.'

2 个答案:

答案 0 :(得分:1)

尝试一下,

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
}()

答案 1 :(得分:0)

更改为

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

make.center.equalToSuperview()

代替

make.center.equalTo(self.contentView)
相关问题