How to load viewcontroller without button in storyboard?

爱⌒轻易说出口 提交于 2020-01-01 19:16:33

问题


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?


回答1:


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:


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:

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

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

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.



来源:https://stackoverflow.com/questions/12499695/how-to-load-viewcontroller-without-button-in-storyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!