Jimbob12505
Jimbob12505

Reputation: 13

How To Programatically Create A Button Action

I'm a new developer to Xcode and I've been struggling getting a hang of it. For my application I was creating a horizontal scroll view with buttons inside of it. In viewDidLoad() I create my scrollView and 3 different buttons within it just fine but I'm not quite sure how to give the buttons an Action. I want it so that if you tap on a certain button, it will bring you to that specific view controller Here's the code I wrote

Upvotes: 0

Views: 113

Answers (2)

k-thorat
k-thorat

Reputation: 5123

Create func to handle touches. Since you are doing in code you don't need to add @IBAction.

@objc
func buttonTapped(_ sender: Any?) {
    guard let button = sender as? UIButton else {
        return
    }
    print(button.tag)
}

Add target to button

button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

You can use same target for all your buttons. Add different tags to each button so you know which one was touched.

https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget

Upvotes: 1

congnd
congnd

Reputation: 1274

You can use addTarget(_:action:for:) https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget

class ViewController: UIViewController {

  override func viewDidLoad() {
    super.viewDidLoad()

    let aButton = UIButton(type: .system)
    aButton.setTitle("Tap me", for: .normal)
    aButton.addTarget(self, action: #selector(onTapButton), for: .touchUpInside)
  }

  @objc func onTapButton() {
  
  }
}

Upvotes: 1

Related Questions