简体   繁体   中英

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:

view.addSubview(tbutton)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM