Moving between XIBs iOS

梦想的初衷 提交于 2019-12-25 17:44:38

问题


I have a view-based application with three xib files, each with its own view controllers. How do I change from one to another? I use this to move from xib 1 to xib 2, but when I use the same code to move from xib 2 to xib 1, i get a EXC_BAD_ACCESS on the [self presentModal....] line.

MapView *controller = [[MapView alloc] initWithNibName:@"MapView" bundle:nil];

controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

[self presentModalViewController:controller animated:YES];

How can I freely move from one xib to another?


回答1:


What I think you are trying to do is is present a modal view and then dismiss it, right? If that is the case then you put the code below in the method that you use to dismiss it(e.g. -(IBAction)dissmissModalView)

[self.parentViewController dismissModalViewControllerAnimated:YES];

Hopefully that works. Let me know.




回答2:


initWithNibName isn't really necessary... you can change that to nil.

So, here is the correct code (without animation):

MapView *mapView = [[MapView alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:mapView animated:NO];

You should not be receiving EXC_BAD_ACCESS when trying to go back to view 1 using present. If you cannot resolve it, just use this instead:

[self dismissModalViewControllerAnimated:YES];

The second view controller will disappear and the first view controller will be visible again.




回答3:


Note that presenting modal view controllers like the other answers here will mean that you have an ever-accumulating stack of view controllers. Use the application long enough and it will crash.

Instead, you can swap out the view from the application's window. Here's one way of doing that:

Add a data member to your app delegate to store the current view:

@class MyAppDelegate : NSObject <...>
{
    UIViewController* currentVC;
}

and add a message there to swap VCs:

-(void)setCurrentVC:(UIViewController*)newVC
{
    if (newVC==currentVC) return;
    if (currentVC!=nil)
        [currentVC.view removeFromSuperview];
    currentVC = newVC;
    if (newVC!=nil)
        [self.window addSubview:newVC.view];
 }

and to swap from one screen to another:

MapView* mapView = [[MapView alloc] init];
[[[UIApplication shared] delegate] setCurrentVC:mapView];


来源:https://stackoverflow.com/questions/7542143/moving-between-xibs-ios

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