Saturday, September 23, 2017

UIButton Selector Error with Swift 4: Argument of '#selector' refers to instance method that is not exposed to Objective-C

Swift 4 (Xcode 9.0) does not work with the below Swift 3 code while drawing a UIButton:


The error message says that:

Argument of '#selector' refers to instance method 'click()' that is not exposed to Objective-C

Add '@objc' to expose this instance method to Objective-C

By clicking the "Fix" button, Xcode automatically fix this error by placing '@objc' in front of func click() as below:



The complete code to draw a button that prints a message while touching it:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
        button.center = view.center
        button.setTitle("Press", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.setTitleColor(.cyan, for: .highlighted)
        button.addTarget(self, action: #selector(click), for: UIControlEvents.touchUpInside)
        view.addSubview(button)
    }
    @objc func click() {
        print("Pressed!")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


1 comment: