【问题标题】:NSLAyoutConstraints not applied for UIView in UICollectionViewCellNSLAyoutConstraints 未应用于 UICollectionViewCell 中的 UIView
【发布时间】:2019-02-02 10:24:44
【问题描述】:

所以我试图在 UICollectionViewCell 中约束视图,但似乎根本没有应用约束

这是我的自定义单元类:

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

}

约束被完全忽略,我得到一个完全白屏

注意:当我尝试添加标签时,我的自定义单元格连接正确,即使有约束它也能正常工作

【问题讨论】:

  • 您能否检查控制台中是否记录了冲突/不明确的约束?
  • 我有以下日志:无法同时满足约束。可能以下列表中的至少一个约束是您不想要的。
  • 那么有冲突的约束。您必须仔细检查这些日志和您的限制,以确定哪些是冲突的。
  • 我尝试了一个小时左右:(

标签: ios swift autolayout nslayoutconstraint


【解决方案1】:

当我添加的时候问题已经解决了

cardView.translatesAutoresizingMaskIntoConstraints = false

就在我的约束之前... 但是为什么当我以这种方式初始化我的 UIView 时它不起作用

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

有人知道吗?

编辑:正如您在 cmets 中看到的那样,问题在于我有

return UIView()

而不是

return cardView

在我的 cardView 变量中...

【讨论】:

  • 因为你没有返回cardView。您刚刚初始化了另一个 UIView 并且从未使用过 cardView
  • 天啊!我一开始就这样做是为了关闭错误,但我已经忘记了......谢谢男人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多