g_1_k
g_1_k

Reputation: 489

Swift add show action to button programmatically

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

Upvotes: 25

Views: 109543

Answers (7)

Navdeep Paliwal
Navdeep Paliwal

Reputation: 379

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)
}

Upvotes: 5

Amr Angry
Amr Angry

Reputation: 3831

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
 }

Upvotes: 6

Hari c
Hari c

Reputation: 1159

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)
        }
    }

Upvotes: 57

Mukul Sharma
Mukul Sharma

Reputation: 51

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)
}

Upvotes: 3

Alexey
Alexey

Reputation: 2164

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
}

Upvotes: 2

Roberto Frontado
Roberto Frontado

Reputation: 438

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
}

Upvotes: 10

Muhammad Raheel Mateen
Muhammad Raheel Mateen

Reputation: 610

  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")
  }

Upvotes: 20

Related Questions