我一直在尝试以编程方式将约束添加到 View 中,我也以编程方式将约束添加到 View Controller 中。然而,似乎没有遵守这些限制。
该 View 已添加到 View Controller 的 Storyboard中,但直到稍后才真正添加到 View Controller 的 View 中(请参见下面的屏幕截图)。
我尝试添加各种约束,但到目前为止没有一个起作用。我现在已将其简化为下面的单个约束,但即使这样也行不通。我做错了什么?
@IBOutlet var loadingView: LoadingView!
override func viewDidLoad() {
super.viewDidLoad()
displayLoadingView(true)
}
func displayLoadingView(display: Bool) {
if display {
view.addSubview(loadingView)
let widthConstraint = NSLayoutConstraint(item: loadingView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50.0)
view.addConstraint(widthConstraint)
}
}
最佳答案
将 translatesAutoresizingMaskIntoConstraints = false
设置为您以编程方式设置约束的任何 View 。
来自 apple doc :
将AutoresizingMaskIntoConstraints 转换为
If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.
关于ios - 以编程方式添加的约束不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122549/