我在按下按钮时运行下面的代码,但是似乎没有遵守底部约束。 subview (bandCardView)溢出父 View (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))
}
最佳答案
确保您已将 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
或
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
之间的关系是实例 - 实例变量,您这样做的方式并不好。最好在它自己的类中进行约束,或者创建一个自定义初始化程序,它只会为您调整常量。
关于swift - 未遵守程序约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44074872/