[英]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):我创建了一个自定义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")
}
}
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.出于某种原因,我遇到了contentView
和groupLabel
不在同一个视图层次结构中的错误,但它们是 - 如您所见,我已将groupLabel
作为子视图添加到contentView
中。 Any reason for hitting this error?遇到此错误的任何原因? I gave it a shot with regular Atuolayout API as well, instead of SnapKit, and no such luck.我也用常规的 Atuolayout API 试了一下,而不是 SnapKit,但没有这样的运气。 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
.我还尝试了equalToSuperview
约束,而不是上面显示的约束,但正如预期的那样,它也会引发相同的错误 - groupLabel
的 superview 返回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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.