Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding target to UIButton without @objc reference

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???

like image 910
Subha Sanket Samanta Avatar asked Sep 17 '25 12:09

Subha Sanket Samanta


1 Answers

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

like image 180
VoidLess Avatar answered Sep 21 '25 08:09

VoidLess