所以我试图约束 UICollectionViewCell 内的 View ,但似乎约束根本没有应用
这是我的自定义单元类:
class MyCustomCell: UICollectionViewCell {
var message: String?
var messageView: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .black
label.textAlignment = .left
label.numberOfLines = 0
return label
}()
var cardView: UIView = {
var cardView = UIView()
cardView.translatesAutoresizingMaskIntoConstraints = false
return UIView()
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(cardView)
cardView.addSubview(messageView)
setupCardView()
setupMessageLabel()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupCardView() {
NSLayoutConstraint.activate([
cardView.topAnchor.constraint(equalTo: self.topAnchor, constant: 5),
cardView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
cardView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 10),
cardView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10)
])
cardView.layer.cornerRadius = 20.0
cardView.layer.shadowColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
cardView.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
cardView.layer.shadowRadius = 12.0
cardView.layer.shadowOpacity = 0.7
cardView.backgroundColor = #colorLiteral(red: 0.7490196078, green: 0.3529411765, blue: 0.9490196078, alpha: 1)
}
}
完全忽略约束,我得到一个完全白色的屏幕
注意:当我尝试添加标签时,我的自定义单元已正确接线,即使有限制它也能正常工作
最佳答案
当我添加后,问题现在已经解决了
cardView.translatesAutoresizingMaskIntoConstraints = false
就在我受到限制之前... 但是为什么当我这样初始化 UIView 时它不起作用
var cardView: UIView = {
var cardView = UIView()
cardView.translatesAutoresizingMaskIntoConstraints = false
return UIView()
}()
有人有什么想法吗?
编辑:正如您在评论中看到的,问题是我有
return UIView()
而不是
return cardView
在我的cardView变量中...
关于ios - NSLAyoutConstraints 不适用于 UICollectionViewCell 中的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54492108/