程序式约束不是正确的

时间:2017-05-19 16:30:08

标签: swift constraints nslayoutconstraint

我在按下按钮时运行以下代码,但是似乎没有遵守底部约束。子视图(bandCardView)溢出父视图(formVw)的底部。如何遵守这些限制?

 @objc private func cardBtnTouch(){
        self.bandAccountView?.bankBtn.setSelected(selected: false)
        self.bandAccountView?.cardBtn.setSelected(selected: true)

        self.bandAccountView?.selectLbl.isHidden = true
        for subview in self.bandAccountView!.formVw.subviews{
            subview.removeFromSuperview()
        }
        self.bandAccountView!.formVw.addSubview(bandCardView!)
        self.bandAccountView!.formVw.addConstraint(NSLayoutConstraint(item: self.bandAccountView!.formVw, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: bandCardView!, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0))
        self.bandAccountView!.formVw.addConstraint(NSLayoutConstraint(item: bandCardView!, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.bandAccountView!.formVw, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0.0))
        self.bandAccountView!.formVw.addConstraint(NSLayoutConstraint(item: bandCardView!, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.bandAccountView!.formVw, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 0.0))
        self.bandAccountView!.formVw.addConstraint(NSLayoutConstraint(item: self.bandAccountView!.formVw, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: bandCardView!, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0.0))
    }

1 个答案:

答案 0 :(得分:2)

确保将translatesAutoresizingMaskIntoConstraints设置为false

在iOS 9之后,还有一个easier way来编写约束。

添加一个没有任何常量的约束:

self.bandAccountView!.formVw.addConstraint(formVw.topAnchor.constraint(equalTo:
 bandCardView.topAnchor)

使用常量添加一个约束:

self.bandAccountView!.formVw.addConstraint(formVw.topAnchor.constraint(equalTo: 
bandCardView.topAnchor, constant: 10)

添加多个约束:

self.bandAccountView!.formVw.addConstraints([formVw.topAnchor.constraint(equalTo:
 bandCardView.topAnchor),formVw.bottomAnchor.constraint(equalTo:
 bandCardView.bottomAnchor),formVw.leadingAnchor.constraint(equalTo: 
 bandCardView.leadingAnchor),formVw.trailingAnchor.constraint(equalTo:
 bandCardView.trailingAnchor)]

注意:

如果您曾写过:

self.bandAccountView!.formVw.leadingAnchor.constraint(equalTo:
formVw.leadingAnchor, constant: 0)

然后你实际上忘了"添加/激活约束"。要修复它,您必须执行以下操作:

self.bandAccountView!.formVw.leadingAnchor.constraint(equalTo:
formVw.leadingAnchor, constant: 0).isActive = true

OR

let leadingConstraint = self.bandAccountView!.formVw.leadingAnchor.constraint(equalTo:
formVw.leadingAnchor, constant: 0)
leadingConstraint.isActive = true // do this whenever you need
leadingConstraint.isActive = false // if you don't need it...

或者只是像第一个代码段一样

另外bandAccountView& formVw是实例 - 实例变量,他们认为这样做并不好。在它自己的类中进行约束或者创建一个只为你调整常量的自定义init会好得多。