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

3
  • 2
    Add code as text to your question instead of image. Commented Aug 18, 2020 at 10:09
  • check this.. stackoverflow.com/a/43423784/6783598 Commented Aug 18, 2020 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)) Commented Aug 18, 2020 at 10:33

2 Answers 2

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() {
  
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.