0

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

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 2
    Add code as text to your question instead of image. – Asperi Aug 18 '20 at 10:09
  • check this.. https://stackoverflow.com/a/43423784/6783598 – Ben Rockey Aug 18 '20 at 10:14
  • I see several issues here. First, you're not setting any constraints on any of your views so your UI will not display correctly. Second, you need to add targets to your buttons so that they can respond to events (`button.addTarget(self, action: action: #selector(someObjcMethod), for: .touchUpInside)`) – henrik-dmg Aug 18 '20 at 10:33

2 Answers2

1

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() {
  
  }
}
congnd
  • 1,168
  • 8
  • 13
1

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

k-thorat
  • 4,873
  • 1
  • 27
  • 36