我已经创建了一个自定义的 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")
}
}
不知道为什么,我遇到了一个错误,那就是... contentView
和 groupLabel
不在同一个视图层次结构中,但它们是--我已经添加了 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)