Present View From Storyboard Programmatically - ios

I am very new to using Storyboards, and am trying to learn. In my app, I want to change from one view to another, modally, without pushing any buttons, i.e. timer runs down then performs the action. I added a notification observer in the main view, and in my storyboard, I added a new view controller, and associated the Custom Class with it called URLWebViewController. In code I wrote out:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard_iPhone" bundle:nil];
URLWebViewController *myVC = (URLWebViewController *)[storyboard instantiateViewControllerWithIdentifier:#"URLWeb"];
[self presentViewController:myVC animated:YES completion:nil];
But I get the warning message
Incompatible pointer types sending 'URLWebViewController' to parameter of type 'UIViewController'
Like I said, I am very new to Storyboards, and here is what it looks like currently:

Your screenshot indicates you have not created a segue between the two view controllers. Do so by click-and-drag from one view controller to the other. In the attribute inspector, give your newly-created segue an identifier, i.e., a string that names it.
To trigger this segue programmatically, in your source view controller (the one you are segueing from) just call performSegueWithIdentifier and pass in the identifier you chose.

It's really simple! I didn't understand the order but let's say you want to pass from ViewController to WebViewController (the name from your storyboard)..Just ctrl-drag from ViewController to WebViewController to create a segue and select modal as the type.
Now click on the line that connects your view controllers and in the right panel give it an identifier. Now in your code just use the method performSegueWithIdentifier using the identifier you wrote.

Related

iOS - Pushing to a View Controller that is not in the Storyboard

Ok, first let's name things:
I have a table view in my root view controller wich we'll call "HomeViewController". In that table view each cell tap will push a different view controller. This collection of view controllers we'll call "DetailViewControllers".
I am perfecly aware that I can make this work by simply loading and pushing each of the DetailViewControllers programmatically inside the didSelectRowAtIndexPath method. I want to do something different instead using storyboard and a prototype cell and I'm not succeeding, so I'm looking for some advice since I'm not too well versed in storyboards and segues.
The behavior I'm trying to achieve here is:
I'll have a segue from a prototype cell in the table view in my HomeViewController. That segue pushes a "base" view controller, from which every DetailViewController inherits. These view controllers don't have an assigned view controller in the storyboard either.
In the prepareForSegue method I want to cast the 'destinationViewController' to the 'right' class. The app crashes at that point saying it "Could not cast value of type 'BaseTestViewController' to 'TestViewController'.". Which is totally understandable.
So, my question is: is there a way to make a segue work like that?
You can't create segues programatically. Segues don't exist without a storyboard. You can just push to a view controller via loading a nib file.
Here's how you do it.
Let's say you have a nib file containing the layout of the view for the main view of your view controller. We'll name it "Test" for instance.
Go to that nib file, click file's owner.
Change class to the name of your view controller. In my case, I named it ViewController.
Right click on file's owner. Link the outlet of view of your view controller to the view in the nib file.
Then in the view controller where you want to transition to that view controller, you do it like this:
UIViewController *controller = [[UIViewController alloc] initWithNibName:#"Test" bundle:[NSBundle mainBundle]];
[self presentViewController:controller animated:YES completion:nil];
It will present the view controller modally.
If you are embedding a navigation controller then you can do it like this:
[self.navigationController pushViewController:controller animated:YES];
Hope it helps.
Try like this without storyboard segue.
let objDestVC = self.storyboard.instantiateViewControllerWithIdentifier("DestVCStroyboardId") as! DestinationViewController
self.navigationController?.pushViewController(objDestVC, animated: true)

access multiple viewControllers from the main viewControllers programmatically in a storyboard

first part of my question is basic understanding.
I believe the other viewControllers in the storyboard are in a "Non instantiated" form when application is launched, and are launched when they are sequed, please confirm?
Second part how do I programmatically instantiate a sibling UIViewController within the storyboard and optionally create a seque to it. I've found some code from Objective-C (pasting below) but looking for a solution in SWIFT.
MyViewController *myVC = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"MyViewController"];
Your first statement is true to a certain extent. Any controller connected to one that does get instantiated by a relationship segue or an embed segue will also be instantiated (like all the children of a tab bar controller). In your code snippet, you don't need to use storyboardWithName: if you're calling that method from a controller that was created in the same storyboard; you can just use self.storyboard.
var myVC = self.storyboard.instantiateViewControllerWithIdentifier("MyViewController")

Change ViewController

I have a multi-player game where I want it to start after I press a button in the menu. The problem is I don't know how to transit from the menu to the game directly after I start multiplayer.
In ViewController.m
- (IBAction)multiplayer:(id)sender {
[Nextpeer launchDashboard];
}
In AppDelegate.m
-(void)nextpeerDidTournamentStartWithDetails:(NPTournamentStartDataContainer *)tournamentContainer {
UIStoryboard *storyboard = self.storyboard;
ArcadeView *svc = [storyboard instantiateViewControllerWithIdentifier:#"arcade"];
[self presentViewController:svc animated:YES completion:nil];
srandom(tournamentContainer.tournamentRandomSeed);
[tournamentContainer tournamentIsGameControlled];
}
I'm getting the error of
"Property'storyboard'not found on object of type 'AppDelegate *' and
"No visible #interface for 'AppDelegate' declares the selector
'presentViewController:animated:completion:'"
How do I change from one ViewController to another ViewController using storyboard?
Normally in cocos2d, I would do like this:
CCScene *gameplayScene = [CCBReader loadAsScene:#"GamePlay"];
[[CCDirector sharedDirector] replaceScene:gameplayScene];
What's the equivalent?
How do i change from one ViewController to another ViewController using storyboard?
Typically, you'd use a segue to switch from one view controller to another. You can create a segue in your storyboard, connect it to a button, and the button will automatically trigger the segue and transition to the next view controller. As part of the segue process, the existing view controller will get a chance to "prepare" for the segue, at which point it can clean up after itself as necessary and also provide any information that the next view controller might need. Read all about it in the docs for -[UIViewController prepareForSegue:sender:].
There are a number of different ways that you can transition from one view controller to another, of course. You can push a new view controller onto a navigation stack, have a tab bar controller switch between several view controllers, present a view controller, simply remove one view controller's view hierarchy from the window and install the new one, and so on. Many of the possible transitions are provided by existing segue types, but you can also create your own custom transitions by creating your own segues.
If all this is new to you, you should probably spend some time reading through View Controller Programming Guide for iOS.

Creating a central log out view controller in storyboard

I am working with Parse, and one thing I have implemented in my app is their built in PFLogInViewController. This controller will be presented at two times in the application - when the app first starts and the user is not logged in, and when the user taps the "Log out" button of my application (logging out takes them back to the PFLogInViewController, as you are required to sign in to use the app). I would like to set this up using Storyboard, as that is how the rest of my app is laid out. How could I set up a central view controller (a PFLogInViewController) that is accessed at these two times? I have already Subclassed PFLogInViewController and set it up, I just need advice on how to place it in Storyboard and how to connect it to my views. To make this question help as many people as possible, the general theme of my question is how does one establish a central Login/ViewController that can be accessed at different points in the application using Storyboard. Attached is the basic idea of what I'm trying to accomplish. I haven't been able to successfully segue to the initial TabBarController, and I'm not sure how I should make the LoginController the initial ViewController if I can't segue. I am programming in Swift, if it matters.
There are a few ways to do this depending upon your application. One way is drop a UIViewController onto the storyboard, but don't wire it up to anything (no segue). Create a storyboard id for it such as "MyLoginVC". Do the necessary subclassing of UIViewController and attach the class to your VC. Then, when you want to display the VC simply do the following or wire this up to your logout button
id destinationVC = [self.storyboard instantiateViewControllerWithIdentifier:#"MyLoginVC"];
[self.navigationController pushViewController:destinationVC animated:YES];
In addition, if you want to show the login VC as the very first VC when you launch your app, then perhaps in your AppDelegate
// Load Root view controller
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
self.rootVC = [storyboard instantiateInitialViewController];
self.window.rootViewController = _rootVC;
[self.window makeKeyAndVisible];
// Load Login view controller
id initialVC = [storyboard instantiateViewControllerWithIdentifier:#"MyLoginVC"];
[initialVC setModalPresentationStyle:UIModalPresentationFullScreen];
[_rootVC presentModalViewController:initialVC animated:NO];
When you finish with your login VC (i.e. successful login) then within login VC
[self dismissViewControllerAnimated:NO completion:nil];
and alternatively instantiate your first VC with something similar to the following from within login VC. Note, since you loaded the root VC above first, it is already there with the login VC sitting over it. When you dismiss login VC, the underlying root VC should be ready to rock and roll. Otherwise you can do the following:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
RootTabBarController *tbController = (RootTabBarController *)[self.storyboard instantiateViewControllerWithIdentifier:#"rootTabBarController"];
[self presentViewController:tbController animated:YES completion:NULL];
}
I think what you want is an unwind segue. Here are the instructions I follow for an unwind segue: https://github.com/bradley/iOSUnwindSegueProgramatically
If the link dies, here is what it said:
In your storyboard create two view controllers.
Subclass UIViewController twice, once for each of the view controllers in your storyboard.
Connect these view controllers to the view controllers in your storyboard.
Make a segue between the first view controller and the second by control+dragging from the first to the second.
Click on the segue you created and give it an identifier in the attributes inspector.
Make a button on the first view controller and link it to an IBAction in its UIViewController subclass.
When this button is pressed, the second storyboard should appear. To make this happen (we are doing it programatically) put the following into the implementation of the action you just created:
[self performSegueWithIdentifier:#"nameOfTheSegueBetweenOneAndTwo" sender:self];
Create a second method in the implemention of the first view controller with the following:
- (IBAction)returnToStepOne:(UIStoryboardSegue *)segue {
NSLog(#"And now we are back.");
}
This method will work to unwind any view controller back to this view controller. Notice that we implement the method in the view controller we wish to return to.
Go back to the storyboard. Focus in on the second view controller. If it is active, you should see a dark bar beneath it with 3 symbols on it. One of these is orange and when hovered over will show the name of the UIViewController subclass that this view controller represents. Control drag from this symbol woth the green symbol that means 'Exit'. You should see all available segue unwinds, which XCode automatically enumerates when you create segue unwind implementations inside UIViewController subclasses that you have shown on your stroryboard. Hence, you should see the segue 'returnToStepOne' as an option. Select it.
In your storyboard's document outline, find the section for the second view controller. You should see an item listed below it with a grey symbol that says something like "Unwind segue from ... to Exit." Click on this item.
Important and easily missed step follows!
On the right side of your storyboard, in the attributes inspector, you should see two fields. One for 'Identifier' and one for 'Action'. In most cases, the 'Action' field will have the text 'returnToStepOne:', which is what we want, but the 'Identifier' field will be blank. Fill this field with the text: 'returnToStepOne' (note that we leave out the colon).
Create a button on the second view controller and link it to an IBAction in its UIViewController subclass.
In the implementation for the method you just created, put the following code:
[self performSegueWithIdentifier:#"returnToStepOne" sender:self];
Run the application. You should now be able to unwind from the second view controller to the first.

Firing a segue from a different view

I have a segue that navigates from FirstViewController to SecondViewController. This happens by the press of a button. The code for the button is
- (IBAction)segue:(id)sender {
[self performSegueWithIdentifier:#"myIdentifier" sender:self];
}
This happens correctly when i press the button.
What i am trying to do is fire this method from another view. I tried doing
FirstViewController fvc = [[FirstViewController alloc] init];
[fvc segue:nil];
When i try this, I get the error message, Reciever has no segue with identifier 'myIdentifier'
How do i fire this segue programatically from another view?
There are a few issues here, but they boil down to a couple of key points:
Segues are a storyboard thing, so view controllers only "know" about segues if they're instantiated from a storyboard.
A view controller must be onscreen to perform a segue.
Segues are transitions from one specific view controller to another specific view controller.
So, in your snippet:
FirstViewController fvc = [[FirstViewController alloc] init];
[fvc segue:nil];
The first problem is that alloc-init-ing gives you an instance of FirstViewController that doesn't know anything about the storyboard it came from, so it doesn't know anything about segues. (This alone could be fixed using [instantiateViewControllerWithIdentifier:][1], but that doesn't solve your whole problem.) A second problem is that this instance doesn't fit anywhere into the UI hierarchy -- it hasn't been presented as a modal view controller, it's not the top view controller in the current navigation controller, it's not the visible window's root view controller, etc. In order to transition the screen from one view to another, the first view needs to be onscreen.
What it sounds like you want to do is transition from what's currently onscreen to the target of this segue. But the notion of a storyboard segue isn't just a transition with a destination -- it's a source, a destination, and a transition or relationship between them. If you have a different source view, you need a different segue. So, if you already have a segue from FirstViewController to SecondViewController, and you want to make a similar transition from OtherViewController (assuming that's the one onscreen now) to SecondViewController, you need to make a second segue connecting OtherViewController to SecondViewController.

Resources