如何不使用情节提要在两个视图之间添加UIButton?

时间:2018-08-02 06:39:24

标签: ios swift

我无法理解在何处添加子视图,以便按钮可以位于现有视图的中间。

1 个答案:

答案 0 :(得分:2)

这对我有用。 (快速4.0)

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let yourView = self.view
    addButtonOnCentral(yourView!)
}

func addButtonOnCentral(_ view:UIView) {
    let btn = UIButton.init()
    btn.backgroundColor = UIColor.yellow
    btn.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(btn)

    let widthConstraint = NSLayoutConstraint(item: btn, attribute: .width, relatedBy: .equal,
                                             toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 20)

    let heightConstraint = NSLayoutConstraint(item: btn, attribute: .height, relatedBy: .equal,
                                              toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 30)

    let xConstraint = NSLayoutConstraint(item: btn, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)

    let yConstraint = NSLayoutConstraint(item: btn, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)

    NSLayoutConstraint.activate([widthConstraint, heightConstraint, xConstraint, yConstraint])
}