An example, which I think it illustrates how Selector is different than a function pointer:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
makeButton(vControl: self, action: #selector(AnotherClass.buttonActionWithSender(_:))) //<-
}
@objc func buttonAction(sender: UIButton!) {
print("Button tapped")
}
}
func makeButton(vControl: ViewController, action aSelector: Selector) {
let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.backgroundColor = .green
button.setTitle("Test Button", for: .normal)
button.addTarget(vControl, action: aSelector, for: .touchUpInside)
vControl.view.addSubview(button)
}
class AnotherClass: NSObject {
@objc func buttonActionWithSender(_ sender: UIButton) {
print("\(type(of: self))-\(#function)")
}
}
Please see what will happen with this code.
Topic:
UI Frameworks
SubTopic:
UIKit
Tags: