How to push and present to UIViewController programmatically without segue in iOS Swift 3

83,609

Solution 1

Push

do like

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("NewsDetailsVCID") as NewsDetailsViewController 
 vc.newsObj = newsObj
 navigationController?.pushViewController(vc,
 animated: true)

or safer

  if let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NewsDetailsVCID") as? NewsDetailsViewController {
        viewController.newsObj = newsObj
        if let navigator = navigationController {
            navigator.pushViewController(viewController, animated: true)
        }
    }

present

   let storyboard = UIStoryboard(name: "Main", bundle: nil)
   let vc = self.storyboard?.instantiateViewControllerWithIdentifier("NewsDetailsVCID") as! NewsDetailsViewController
      vc.newsObj = newsObj
           present(vc!, animated: true, completion: nil)  

or safer

   if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NewsDetailsVCID") as? NewsDetailsViewController
     {

     vc.newsObj = newsObj
    present(vc, animated: true, completion: nil)
    }

Solution 2

With an elegant way.

Create an Navigatable protocol:

protocol Navigatable {
    /// Storyboard name where this view controller exists.
    static var storyboardName: String { get }


    /// Storyboard Id of this view controller.
    static var storyboardId: String { get }

    /// Returns a new instance created from Storyboard identifiers.
    static func instantiateFromStoryboard() -> Self
}

Create a default instantiate controller implementation:

/**
 Extension of Navigatable protocol with default implementations.
 */
extension Navigatable {
    static func instantiateFromStoryboard() -> Self {
        let storyboard = UIStoryboard(name: self.storyboardName, bundle: nil)
        guard
            let viewController = storyboard
                .instantiateViewController(withIdentifier: self.storyboardId) as? Self else {
                    fatalError("Cannot instantiate the controller.")
        }

        return viewController
    }
}

Extends the UIViewController to push a view controller:

extension UIViewController {
    /**
     Pushes a view controller of the provided type.

     - Parameter viewControllerType: Type of view controller to push.
     - Parameter completion: Function to be executed on completion.
     Contains the view controller that was pushed when successful and nil otherwise.
     */
    func pushViewControllerOfType<T: Navigatable>(viewControllerType: T.Type, completion: (T) -> Void) {
        let viewController = T.instantiateFromStoryboard()
        if let vc = viewController as? UIViewController {
            self.pushViewController(vc, animated: true)
        }
        completion(viewController)
    }


    /**
     Pushes a view controller of the provided type.

     - Parameter viewControllerType: Type of view controller to push.
     */
    func pushViewControllerOfType<T: Navigatable>(viewControllerType: T.Type) {
        self.pushViewControllerOfType(viewControllerType: viewControllerType) { _ in }
    }
}

Then you can use the Navigatable protocol for a specific view controller.

class MySuperViewController {
   override func viewDidLoad() {
      ...
   }
   // ...
}
extension MySuperViewController: Navigatable {
    static var storyboardName: String {
        return "Main"
    }

    static var storyboardId: String {
        return "MySuperViewControllerId" // From your story board name Main
    }
}

// Instantiate your controller
let vc = MySuperViewController.instantiateFromStoryboard()

// Or
//
// Push your view controller

// testViewController.swift

self.pushViewControllerOfType(viewControllerType: MySuperViewController)

Solution 3

//Create object of view controller 
let obj = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerIdentifier”) as! ViewControllerName

//Push Controller
self.navigationController?.pushViewController(obj, animated: true)

//Present Controller
self.navigationController?.present(obj, animated: true, completion: nil)
Share:
83,609

Related videos on Youtube

reza_khalafi
Author by

reza_khalafi

PHP,iOS,Android developer Laravel framework. Objective-C. Swift. Java. Kotlin. From IRAN

Updated on July 23, 2022

Comments

  • reza_khalafi
    reza_khalafi almost 2 years

    I am using this code for push SHOW and MODALLY programmatically in iOS Objective C.
    And now want to know about Swift 3.

    NewsDetailsViewController *vc =  instantiateViewControllerWithIdentifier:@"NewsDetailsVCID"];
    vc.newsObj = newsObj;
    //--this(SHOW)
    [self.navigationController pushViewController:vc animated:YES];  
    //-- or this(MODAL)
    [self presentViewController:vc animated:YES completion:nil];  
    
  • vaibhav
    vaibhav over 7 years
    can you explain or safer part here comparatively, +1 for that.
  • Meshach
    Meshach about 7 years
    @vaibhav "or safer" refers to handling the potential optional 'nil' case while instantiating the view controller. "if let" is a classic way to handle the optional nil in swift.
  • iOS Developer
    iOS Developer over 5 years
    what if i dont have any view controler in storyboard but all is i am doing programatically then what should i do to call or declare view controller's id
  • Anbu.Karthik
    Anbu.Karthik over 5 years
    @iOSDeveloper- if its progrmactially you can directly call the VC
  • Rakesha Shastri
    Rakesha Shastri over 5 years
    Why do you need to safely unwrap it? Both of them result in the same thing happening - if the navigationController is present, it pushes a view controller, otherwise nothing happens.