#selector not compatible with closure?

I tried to implement a custom function with closure. But this is not supported #selector.

Here is an example:

class Core: NSObject {

    static let shared:Core = Core.init()


    func button(viewController: UIViewController, button: UIButton, title: String, color: UIColor, completion: () -> Void) {

        button.layer.cornerRadius = button.bounds.width / 2
        button.setTitle(title, for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = color
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.addTarget(viewController, action: #selector(completion()), for: .touchUpInside)
    }
}

Xcode gives me a question about build time:

The argument '#selector' does not refer to a method, @bjc ', a property, or an initializer

+3
source share
2 answers

- , , , Objective C. #selector(SomeClass.SomeMethod(withParam:AndParam:), , . , , C, : "SomeMethodwithParam:AndParam:".

, , , . , Objective C , .

, . , , , , Objective C ( @objc, ).

+3

. A #selector - - . .

typealias . :

// Declare your completion as typealias
typealias YourCompletion = () -> Void

// At top of your class
var completion: YourCompletion?

// Then in your function declare the completion: parameter to be of type YourCompletion
func button(viewController: UIViewController, button: UIButton, title: String, color: UIColor, completion: YourCompletion) {

    // Assign completion as property
    self.completion = completion

    // Configure your button
    button.layer.cornerRadius = button.bounds.width / 2
    button.setTitle(title, for: .normal)
    button.setTitleColor(UIColor.white, for: .normal)
    button.backgroundColor = color
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)

    // Have your button action be the function you'll make below
    button.addTarget(viewController, action: #selector(self.callCompletion), for: .touchUpInside)
}

func callCompletion() {
    if let completion = self.completion {
        // Call completion
        completion()
    }
}
+1

Source: https://habr.com/ru/post/1675280/


All Articles