简体   繁体   中英

Custom UITableViewCell - can't seem to add subview

I've created a custom UITableViewCell class as shown below (programmatically - no use of storyboards for this):

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

And for some reason, I'm hitting the error that contentView and groupLabel are not in the same view hierarchy, but they are - I've added groupLabel as a subview to contentView as you can see. Any reason for hitting this error? I gave it a shot with regular Atuolayout API as well, instead of SnapKit, and no such luck. Feel like this might be a small mistake I'm missing. I've also attempted the equalToSuperview constraint, rather than what I have shown above, but as expected it also throws the same error - groupLabel 's superview returns nil .

Error:

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.'

Try this,

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),
    ])

}

change your grouplabel like this

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

Change to

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

or

make.center.equalToSuperview()

Instead of

make.center.equalTo(self.contentView)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM