Home > Blockchain >  weird behavior of swift when I try to add a button using a closure
weird behavior of swift when I try to add a button using a closure

Time:02-17

I know I need to replace the let keyword with lazy var for accessing the property otherwise I cannot access the 'self'.
But I found that the button.addTarget can build successfully as below,
Why? Normally if you try to access the property from a closure that needs to be a lazy variable, Am I right?
For comparison, The testProperty shows red error message as 'Cannot convert value of type '(testController) -> () -> testController' to specified type 'UITabBarController'

import UIKit

class testController: UIViewController {
    
    let actionButton: UIButton = {
        let button = UIButton(type: .system)
        button.addTarget(self,  action: #selector(actionButtonTapped), for: .touchUpInside)
        return button
    }()
    
    let testProperty: UIViewController = {
        let obj: UIViewController = self
        return obj
    }()
    
    @objc func actionButtonTapped() {
        
    }
}

CodePudding user response:

If you check the addTarget signature, you will see the following:

open func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControl.Event)

First parameter target is Any?, so passing (Function) as target compiles fine. It even will work but can lead to weird issues, like opening keyboard will stop the button from calling the action.

CodePudding user response:

You currently think that self refers to the instance.

But no. It refers to the metatype, because of the context—just like in a static method, for example.

The metatype does not respond to the selector so it won't work.

  • Related