【问题标题】:NSLayoutConstraints programmaticallyNSLayoutConstraints 以编程方式
【发布时间】:2021-06-17 22:10:34
【问题描述】:

我想以编程方式向视图添加约束。

这就是我所做的:

extension UIView {
  func bottomToTop(other: UIView) {
     self.translatesAutoresizingMaskIntoConstraints = false
     other.translatesAutoresizingMaskIntoConstraints = false
     let constraint = NSLayoutConstraint(
        item: self,
        attribute: .bottom,
        relatedBy: .equal
        toItem: other,
        attribute: .top,
        multiplier: 1.0,
        constant: 0.0
    )
    superview?.addConstraint(constraint)
    constraint.isActive = true
  }
}


let label = UILabel()
label.text = "Lenaaaaa"
label.sizeToFit()
label.backgroundColor = .green

let label1 = UILabel()
label1.text = "Lena 2"
label1.sizeToFit()
label1.backgroundColor = .green

let uiView = UIView(frame: frame) (not zero)
uiView.addSubview(label)
uiView.addSubview(label2)

label.bottomToTop(label2)

为什么我会这样?

【问题讨论】:

    标签: ios nslayoutconstraint


    【解决方案1】:

    为什么我会这样?

    因为你的约束是模棱两可的。一旦您添加了影响视图的 一个 约束,您必须根据自动布局完全 描述该视图的位置和大小。 (而且你必须停止谈论 .frame,因为它现在实际上毫无意义。)

    所以,你只说了

    label.bottomToTop(label2)
    

    但是你还没有说label的顶部在哪里,label的左边在哪里,label2的左边在哪里,等等。因此,自动布局引擎绝望地举起了手。

    您可以通过运行您的应用程序并使用 view 调试器 轻松发现这一点。它会显示很大的感叹号,告诉您您的自动布局问题是什么。

    【讨论】:

    • 您的代码在其他方面也有错误。例如,你永远不应该同时说addConstraintconstraint.isActive = true;他们做同样的事情,第二个做得更好。
    • 另外,你的代码对我来说毫无意义,因为它谈论的 uiView 甚至从未进入界面,所以我不明白你为什么说 anything。如果这是操场代码,请停止它;使用真实的项目。
    猜你喜欢
    • 2016-11-23
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    相关资源
    最近更新 更多