簡體   English   中英

自定義 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的 superview 返回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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM