简体   繁体   English

NSLAyoutConstraints不适用于UICollectionViewCell中的UIView

[英]NSLAyoutConstraints not applied for UIView in UICollectionViewCell

So I am trying to constraint a view inside a UICollectionViewCell but it seems like the constraints are not applied at all 所以我试图约束UICollectionViewCell内的视图,但似乎根本没有应用约束

This is my custom cell class: 这是我的自定义单元格类:

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

} }

The constraints are completely ignored and I get a completely white screen 约束被完全忽略,我得到一个完全白屏

NOTE: My custom cell is wired correctly as I tried to add a label and it works properly even with constraints 注意:在尝试添加标签时,我的自定义单元已正确接线,即使有约束,它也可以正常工作

The problem is solved now when I added 现在,当我添加时,问题就解决了

cardView.translatesAutoresizingMaskIntoConstraints = false

right before my constraints... But why doesn't it work when I initialize my UIView this way 就在我的约束之前...但是为什么当我这样初始化UIView时它不起作用

var cardView: UIView = {
    var cardView = UIView()
    cardView.translatesAutoresizingMaskIntoConstraints = false
    return UIView()
}()

Anyone any idea? 有人知道吗?

EDIT: As you can see in the comments the problem was that I have 编辑:正如您可以在评论中看到的问题是我有

return UIView()

instead of 代替

return cardView

in my cardView variable... 在我的cardView变量中...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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