user1680822
user1680822

Reputation:

How to load viewcontroller without button in storyboard?

I want to load view controller without button. I set the identifier to 10 and tried to use

if(...){ 
//load ViewController2
UIViewController *vc = [[self storyboard] instantiateViewControllerWithIdentifier:@"10"];
[self.navigationController pushViewController:vc];
}

here is my progect http://www.sendspace.com/file/kfjhd5

whats a problem?

Upvotes: 1

Views: 5810

Answers (1)

Rob
Rob

Reputation: 437917

The above code in your question is fine. I know you were asking about how to do this without a button, but the problem with your demonstration was that you used a button, but didn't properly hook it up to the IBAction. Your goNext should be defined in your .h as:

- (IBAction)goNext:(id)sender;

And the implementation should be:

- (IBAction)goNext:(id)sender
{
    UIViewController *vc=[[self storyboard] instantiateViewControllerWithIdentifier:@"10"];
    [self.navigationController pushViewController:vc animated:YES];
}

I presume you created that IBAction manually. In the future it's worth noting that if you control-drag (or right-click drag) from the button down to the assistant editor file, you can automate the creation of your IBAction interfaces, and this sort of error won't happen:

automate creation of IBAction


As an aside, I personally like to use a segue instead, so I first define the push segue between the view controllers themselves. In Xcode 6, one would control-drag from the view controller icon above the scene to the destination scene:

create segue xcode 6

In Xcode versions prior to 6, one would control-drag from the view controller icon in the bar below the scene:

create segue

I then select the segue in Interface Builder and give it a "storyboard identifier" (in this example, I called it pushTo10):

specify segue id

I then have my goNext execute that segue, rather than manually invoking pushViewController:

- (IBAction)goNext:(id)sender
{
    [self performSegueWithIdentifier:@"pushTo10" sender:self];
}

The advantage of that is that my storyboard now visually represents the flow of my app (rather than appearing to have a scene floating out there) and graphical elements like the navigation bar are correctly represented in the storyboard.

You don't have to do it this way, but it's another alternative to be aware of.

Upvotes: 10

Related Questions