如何打开编程的 UIButton (swift4)

How to unwrap programmed UIButton (swift4)

我正在尝试使用编程约束创建一个按钮。我试图不使用故事板。我在打开按钮时遇到问题。我该怎么做?

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

您不需要打开它。使用前需要实例化。

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)

}

使用 ! 声明的任何变量都将被强制解包,这意味着如果您忘记创建实例并使用该变量,它将引发错误并使您的应用程序崩溃。

使用此代码:

import UIKit

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(button)
    setupConstraints()
  }

  lazy var button: UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Button", for: .normal)
    button.backgroundColor = .blue
    //your action here
    button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
    return button
  }()

  private func setupConstraints() {
    button.translatesAutoresizingMaskIntoConstraints = false
    let top = NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 100)
    let left = NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: view, attribute: .left, multiplier: 1, constant: 50)
    let right = NSLayoutConstraint(item: button, attribute: .right, relatedBy: .equal, toItem: view, attribute: .right, multiplier: 1, constant: -50)
    let height = NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)
    view.addConstraints([top, left, right, height])
  }

  @objc func buttonAction() {
    print("Button has pressed")
  }

}