0

How can I show() or persent() VC on button touch? What code should I write?

SEI4X
  • 33
  • 1
  • 4

1 Answers1

7

First, using Storyboards

If you are working with storyboard. You should connect your button view storyboard.

@IBAction fileprivate func handlePresentingView(_ sender: UIButton) {
  let vc = SecondVC() 
  present(vc, animated: true, completion: nil)
}

Second, programmatically

1: If you are working programmatically in viewDidLoad add the following line.

    mybutton.addTarget(self, action: #selector(handlePresentingVC(_:)), for: .touchUpInside)

2: Your action method

  @objc func handlePresentingVC(_ sender: UIButton) {
    let vc = SecondVC()
    present(vc, animated: true, completion: nil)
  }

In my example, I'm assuming that you don't have a storyboard file for your SecondVC view controller.

If SecondVC is connected to a storyboard view controller, you will need to change the instantiation of your secondVC object inside of your button's action method.

1: Select your SecondVC's view controller in your storyboard.

2: Add a Storyboard ID to it.

3: Change your button's action method to the following.

  @objc func handlePresentingVC(_ sender: UIButton) {
        let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
        let secondVc = storyboard.instantiateViewController(withIdentifier: "SecondVC") as! SecondVC

    present(secondVc, animated: true, completion: nil)
  }

In Swift 5 and iOS 13

The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.

To retain the old style you need to modify the view controller inside of your button's action method like this:

secondVc.modalPresentationStyle = .fullScreen

This is the same for both programmatically created and storyboard created controllers.

Hassan ElDesouky
  • 334
  • 4
  • 17
  • When I use this code, it sent me an Issue: `Attempt to present on whose view is not in the window hierarchy!` – SEI4X Feb 16 '20 at 11:30
  • Can you provide your `viewDidLoad` code as well as your button's action method? – Hassan ElDesouky Feb 16 '20 at 11:36
  • You can try and add the following line in your button's action method: `secondVc.modalPresentationStyle = .fullScreen` – Hassan ElDesouky Feb 16 '20 at 11:39
  • what's the difference between `show` and `present`? I understand the difference when it comes to segues, but not with alerts. https://stackoverflow.com/questions/25966215/whats-the-difference-between-all-the-selection-segues – NitricWare Jan 24 '21 at 10:03