Warning :-Presenting view controllers on detached

2019-01-02 16:56发布

In my app, I am using a navigation controller. Later on in some view I am using presentViewController for showing a zoomed image. Also I am not using a Storyboard or nib.

I am getting this error in iOS 7 only. It works fine in iOS 6 and earlier:

Presenting view controllers on detached view controllers is discouraged

17条回答
看淡一切
2楼-- · 2019-01-02 17:18

Lots of reasons for this warning. Mine is because I have a segue connected from a ViewController to another that will be presented modally. But, the ViewController I am presenting from is being dynamically generated by a PageViewController. Which is why it is detached in the Storyboard. My app isn't going to crash because of it; but I would like to silence the warning.

查看更多
像晚风撩人
3楼-- · 2019-01-02 17:20

Wait for viewDidAppear():

This error can also arise if you are trying to present view controller before view actually did appear, for example presenting view in viewWillAppear() or earlier. Try to present another view after viewDidAppear() or inside of it.

查看更多
刘海飞了
4楼-- · 2019-01-02 17:20

you need to add the view controller that will present the new controller as a child of the parent view controller.

Let's say you have yourMainViewController, then you add a new controller called controllerA, and then you want to present a new controller called controllerB from controllerA

you have to write something like this:

[self addChildViewController:controllerA]; //self is yourMainViewController
[self.view addsubView:controllerA.view]; 

and within controllerA you can present the new controller without warnings

[self presentViewController:controllerB animated:YES completion:nil]; //self is controllerA
查看更多
倾城一夜雪
5楼-- · 2019-01-02 17:29

To avoid getting the warning in a push navigation, you can directly use :

[self.view.window.rootViewController presentViewController:viewController animated:YES completion:nil];

And then in your modal view controller, when everything is finished, you can just call :

[self dismissViewControllerAnimated:YES completion:nil];

查看更多
素衣白纱
6楼-- · 2019-01-02 17:29

Swift 3

For anyone stumbling on this, here is the swift answer.

self.parent?.present(viewController, animated: true, completion: nil)
查看更多
旧人旧事旧时光
7楼-- · 2019-01-02 17:30

Make sure you have a root view controller to start with. You can set it in didFinishLaunchingWithOptions.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    [window setRootViewController:viewController];
}
查看更多
登录 后发表回答