When we make a UIButton programmatically and add a target for its click action. And for the selector we need a function with "@objc" reference, even if we are working in a purely swift project.
override func viewDidLoad() {
let requiredButton = UIButton(frame: CGRect(x: 100, y: 100, width: 50, height: 30))
self.view.addSubview(requiredButton)
requiredButton.addTarget(self, action: #selector(self.buttonTapAction(sender:)), for: UIControl.Event.touchUpInside)
}
@objc func buttonTapAction(sender:UIButton) {
// button action implementation here
}
Is there a way to do this without the "@objC" reference???
If you target iOS 14+ there is new API that you can use without "@objc" references:
override func viewDidLoad() {
let requiredButton = UIButton(frame: CGRect(x: 100, y: 100, width: 50, height: 30), primaryAction: .init(handler: { _ in
// button action implementation here
}))
self.view.addSubview(requiredButton)
}
If you target iOS 13+ you can build UI using SwiftUI with Button controls. SwiftUI is currently internally based on UIKit, but you can write whole apps in swift using SwiftUI without a single "@objc" reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With