Adding a Target to an UIButton

July 28, 2019 ยท 1 minute read

I always seem to forget how to add a target to a button, so that it will automatically run an action or update something immediately. Sometime you just don’t have the brain storage to keep it all in there. So here’s the recipe:

  1. Make sure your button(s) have tags. This make it easier to do different actions for different buttons. Set the tag with code or do it in Storyboard.

    fizzButton.tag = 3
    
  2. Create a method with an @objc so that your button knows what it should do once it is pressed.

    @objc func buttonTapped(sender: UIButton)
    {
    if(sender.tag == 3)
    {
        print("hello, fizz") // Do something here for button with tag = 3
    }
    }
    
  3. Add the addTarget(_:action:for) method on the button in the viewDidLoad() method.

    override func viewDidLoad()
    {
    super.viewDidLoad()
        
    fizzButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    }
    

That’s about it.

Subscribe to my email list for a monthly newsletter and special updates!