自动布局以编程方式快速

时间:2018-07-25 12:02:18

标签: ios swift ios-autolayout

我需要有关自动布局的帮助。对Autolayouts来说是一个非常新的东西,并且没有获得如何以编程方式添加自动布局的方法,而实际上却出现了错误。

添加到视图时,约束的项必须是该视图的后代(或视图本身)。如果在组装视图层次结构之前需要解决约束,则会崩溃。中断-[UIView(UIConstraintBasedLayout)_viewHierarchyUnpreparedForConstraint:]进行调试。 2018-07-25 17:35:19.363248 + 0530

AutoLayoutsProgrammtically [4831:78876] ***由于未捕获的异常'NSGenericException'而终止应用程序,原因:'无法在视图上安装约束。约束是否引用了视图子树之外的内容?那是非法的。约束:UIButton:0x7f8e3ac0a6a0(活动,名称:'|':UIView:0x7f8e3ad09cd0)>视图:>'

下面是代码:

 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])}

2 个答案:

答案 0 :(得分:1)

第一个约束应添加到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)

   ])
  }

}

enter image description here

答案 1 :(得分:0)

您正在向按钮添加约束,但是您应该将约束添加到self.viewYou can check that Gist for full answer.

更改

button.addConstraints([...]) 

view.addConstraints([...])

还要更改titleLabeltitleColor,您应该使用

button.setTitle("dasdasdas", for: .normal)
button.setTitleColor(.white, for: .normal)