我需要自动布局方面的帮助。我是自动布局的新手,不知道如何以编程方式添加自动布局,实际上我遇到了错误。
添加到 View 时,约束项必须是该 View (或 View 本身)的后代。如果在组装 View 层次结构之前需要解决约束,这将崩溃。中断 -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] 进行调试。 2018-07-25 17:35:19.363248+0530
AutoLayoutsProgrammtically[4831:78876] *** 由于未捕获的异常“NSGenericException”而终止应用程序,原因:“无法在 View 上安装约束。约束是否引用了 View 子树之外的内容?那是非法的。约束:UIButton:0x7f8e3ac0a6a0(事件,名称:'|':UIView:0x7f8e3ad09cd0)> View :>'
代码如下:
var button : UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.button)
// self.updateTheChanges()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillLayoutSubviews() {
updateTheChanges()
}
func updateTheChanges() {
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.text = "dasdasdas"
button.backgroundColor = UIColor.black
button.titleLabel?.textColor = UIColor.white
//left edge
let leftEdgeConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: 0)
//right edge
let rightEdgeConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: 0)
// bottom edge
let topEdgeConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.topMargin, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.topMargin, multiplier: 1.0, constant: 10)
// add all constraints
button.addConstraints([leftEdgeConstraint,rightEdgeConstraint,topEdgeConstraint])}
最佳答案
首先应将约束添加到 self.view
import UIKit
class ViewController: UIViewController {
let button = UIButton(type: .system)
override func viewDidLoad() {
super.viewDidLoad()
button.setTitle("mytitle", for: .normal)
button.setTitleColor(.green, for: .normal)
button.backgroundColor = .black
self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
button.leftAnchor.constraint(equalTo: view.leftAnchor),
button.rightAnchor.constraint(equalTo: view.rightAnchor),
button.topAnchor.constraint(equalTo: view.topAnchor,constant:20)
])
}
}
关于ios - 以编程方式快速自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51518384/