Search code examples
iosswift4option-typenslayoutconstraintunwrap

How to unwrap programmed UIButton (swift4)


I am trying to create a button using programmed constraints. I am trying to not use the storyboard. I am having trouble unwrapping the button. How do I do this?

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

Solution

  • You do not need to unwrap it. You need to instantiate it before using it.

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

    Any variable declared with ! will be force unwrapped, meaning that if you forget to create an instance and use the variable, it will throw an error and crash your app.