Chisx
Chisx

Reputation: 1986

How can I programmatically present a view controller modally?

Edit: When solving this problem, I found that it is much easier to start with your UITabBarController, then perform login validation via your AppDelegate.m's didFinishLaunchingWithOptions: method.

Question: This code is in the the application didFinishLaunchingWithOptions: method in my AppDelegate.m

if([result isEqualToString: @"log"])
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *ivc = [storyboard instantiateViewControllerWithIdentifier:@"TabBarControl"];
    [(UINavigationController*)self.window.rootViewController pushViewController:ivc animated:NO];
    NSLog(@"It's hitting log");
}

It simply takes an HTTP response for the user being logged in, and takes them to my TabBarController. The problem is that it's using a push rather than a modal transition to display the page. Since presentModalViewController method is deprecated or deleted in iOS7, how can I programmatically force a modal presentation?

EDIT: )

Upvotes: 21

Views: 55796

Answers (4)

Suragch
Suragch

Reputation: 511616

Swift

This is how you would do it in Swift without referencing the navigation controller:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewController") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)

Change the storyboard name, view controller, and id as needed.

See also how to dismiss a view controller programmatically.

Upvotes: 30

Shahzaib Maqbool
Shahzaib Maqbool

Reputation: 1487

In swift 4.2 you can do it like this. For those who want this answer in swift updated version.

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ExampleViewController")
self.present(controller, animated: true, completion: nil)

Upvotes: 2

Wide Angle Technology
Wide Angle Technology

Reputation: 1222

 let storyB = UIStoryboard(name: "Main", bundle: nil) 
 let secondViewController = 
 storyB.instantiateViewController(withIdentifier: 
 "SecondViewControllerID") as! SecondViewController
 self.present(secondViewController, animated: true, completion: nil)

In the secondViewController use this code to go back.

 self.dismiss(animated: true, completion: nil)

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

In Swift 3/4

     let storyB = UIStoryboard(name: "Main", bundle: nil) 
     let secondViewController = storyB.instantiateViewController(withIdentifier: "SecondViewControllerID") as! SecondViewController
     self.present(secondViewController, animated: true, completion: nil)

Upvotes: 0

Related Questions