Swift4: UIButton not working

Within my app i'm trying to back a UIButton, i just want it to print "this is a test" When i press the button it does the classic button animation, however there is nothing printed in the console.

var tbutton: UIButton = {
    let button = UIButton(type: .system)
    button.frame = CGRect(x: 40.0, y:400.0, width: 300.0, height: 300.0)
    let image = UIImage(named: "backb")
    button.setBackgroundImage(image, for: .normal)
    button.addTarget(self, action: #selector(dothings), for: .touchUpInside)
    return button

@objc func dothings(){
    print("this is a test")


I then add the button into view with:


Is there a section of code i'm missing, or have i coded something wrong?

1 answer

  • answered 2018-01-14 11:22 Andrea Mugnaini

    You shouldn't initialize your button in that way.

    Quoting the Apple documentation from Setting a Default Property Value with a Closure or Function:

    If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values. moreover:

    You also cannot use the implicit self property, or call any of the instance’s methods, hence the problem is here:

    button.addTarget(self, action: #selector(dothings), for: .touchUpInside)

    so to fix the issue you should move the button initialization (or move the addTarget) after your ViewController is fully initialized (eg: viewDidLoad).

    Another way to fix the issue, assuming you are using such button only after viewDidLoad, is to define it as a lazy var:

    A lazy stored property is a property whose initial value is not calculated until the first time it is used