Search code examples
iosswiftviewcontroller

Swift 5. How present or show ViewController on button touch? Without Storyboard (programmatically)


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


Solution

  • 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.