how can I add action to button programmatically. I need to add show action to buttons in mapView. thanks
let button = UIButton(type: UIButtonType.Custom) as UIButton
how can I add action to button programmatically. I need to add show action to buttons in mapView. thanks
let button = UIButton(type: UIButtonType.Custom) as UIButton
You  can go for below code
    `
let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
btn.backgroundColor = UIColor.green
btn.setTitle("Click Me", for: .normal)
btn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
btn.tag = 1
self.view.addSubview(btn) 
for action
 @objc func buttonAction(sender: UIButton!) {
        let btnsendtag: UIButton = sender
        if btnsendtag.tag == 1 {
            dismiss(animated: true, completion: nil)
        }
    }
 
    
     
    
      let button = UIButton(type: UIButtonType.Custom) as UIButton
  button.addTarget(self, action: "action:", forControlEvents: UIControlEvents.TouchUpInside)
  //then make a action method :
  func action(sender:UIButton!) {
     print("Button Clicked")
  }
 
    
    You need to add a Target to the button like Muhammad suggest
button.addTarget(self, action: "action:", forControlEvents: UIControlEvents.TouchUpInside)
But also you need a method for that action
func action(sender: UIButton) {
    // Do whatever you need when the button is pressed
}
 
    
    in addition to the above, the new ios14 introduce
 if #available(iOS 14.0, *) {
     button.addAction(UIAction(title: "Click Me", handler: { _ in
                    print("Hi")
                }), for: .touchUpInside)           
 } else {
     // Fallback on earlier versions
 }
 
    
    For swift 5 users can do by this simple way
cell.followButton.tag = 10
cell.followButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
@objc func buttonAction(sender: UIButton!) {
   let id = sender.tag
   print(id)
}
 
    
    override func viewDidLoad() {
    super.viewDidLoad()  
    let btn = UIButton()
    btn.frame = CGRectMake(10, 10, 50, 50) 
    btn.setTitle("btn", forState: .Normal) 
    btn.setTitleColor(UIColor.redColor(), forState: .Normal) 
    btn.backgroundColor = UIColor.greenColor() 
    btn.tag = 1
    btn.addTarget(self, action: "btnclicked:", forControlEvents: .TouchUpInside)  //add button action
    self.view.addSubview(btn)
}
 
    
     
    
    For Swift 4 use following:
button.addTarget(self, action: #selector(AwesomeController.coolFunc(_:)), for: .touchUpInside)
//later in your AswesomeController
@IBAction func coolFunc(_ sender:UIButton!) {
  // do cool stuff here
}
