Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift add show action to button programmatically

Tags:

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 
like image 519
g_1_k Avatar asked Feb 22 '16 10:02

g_1_k


People also ask

How do you add an action to a button?

Put an action button on your slideOn the Insert tab, click Shapes, and then under Action Buttons at the bottom of the menu, click the button shape that you want to add.

How do I add a target to a button in Swift 4?

If its the own profile of the current user, the button should add the target "go to settings". If its a different user, I want to add a follow/unfollow action. After checking all parameters, my code should work.


2 Answers

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)         }     } 
like image 163
Hari c Avatar answered Nov 27 '22 06:11

Hari c


  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")   } 
like image 21
Muhammad Raheel Mateen Avatar answered Nov 27 '22 07:11

Muhammad Raheel Mateen