我正在尝试使用已编程的约束来创建按钮。我试图不使用情节提要。我在拆开按钮时遇到麻烦。我该怎么做?
import UIKit
var aa: [NSLayoutConstraint] = []
class ViewController: UIViewController {
var btn: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(btn)
let leadingc2 = btn.widthAnchor.constraint(equalToConstant: 80)
let trailingC2 = btn.heightAnchor.constraint(equalToConstant: 50)
let topc2 = btn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: -50)
let bottomc2 = btn.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -250)
aa = [leadingc2,trailingC2,topc2,bottomc2]
NSLayoutConstraint.activate(aa)
}
}
答案 0 :(得分:2)
您不需要打开包装。您需要先实例化它,然后再使用它。
override func viewDidLoad() {
super.viewDidLoad()
btn = UITextField() // Create the button like this before using it.
self.view.addSubview(btn)
btn.translatesAutoresizingMaskIntoConstraints = false
let leadingc2 = btn.widthAnchor.constraint(equalToConstant: 80)
let trailingC2 = btn.heightAnchor.constraint(equalToConstant: 50)
let topc2 = btn.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: -50)
let bottomc2 = btn.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -250)
aa = [leadingc2,trailingC2,topc2,bottomc2]
NSLayoutConstraint.activate(aa)
}
用!
声明的任何变量都将被强制解包,这意味着如果您忘记创建实例并使用该变量,它将抛出错误并使应用程序崩溃。
答案 1 :(得分:0)
使用此代码:
@Entity(name = "my_entit_name")