ios - 以编程方式快速自动布局

标签 ios swift ios-autolayout

我需要自动布局方面的帮助。我是自动布局的新手,不知道如何以编程方式添加自动布局,实际上我遇到了错误。

添加到 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)

   ])
  }

}

enter image description here

关于ios - 以编程方式快速自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51518384/

相关文章:

xcode - 如何使用 NSTimer 进行倒计时?

ios - 在 Swift iOS 中为协议(protocol)分配委托(delegate)时出现编译器错误

ios - 如何在IOS上构建IOS应用程序?

ios - 如何使用自定义键盘 iOS 发送图像

ios - 如何使用 NSLayoutConstraint 将宽度固定到某些 UIView?

swift - 在 ScrollView 中显示多个图标时,是否有比使用自动布局更快的方法来显示图标?

ios - 自动布局视觉格式语言

html - jQuery Mobile 通过离线 iOS 应用程序中的文件加载数据

html - 填充在 iOS 上似乎无法正确显示

ios - 如何为 tableview 上的 webview 内容启用 VoiceOver