我正面临一个问题,而试图unwind使用自定义segue从一个视图控制器作为子添加到另一个视图控制器。
这里是MyCustomSegue.m:
- (void)perform
{
if (_isPresenting)
{
//Present
FirstVC *fromVC = self.sourceViewController;
SecondVC *toVC = self.destinationViewController;
toVC.view.alpha = 0;
[fromVC addChildViewController:toVC];
[fromVC.view addSubview:toVC.view];
[UIView animateWithDuration:1.0 animations:^{
toVC.view.alpha = 1;
//fromVC.view.alpha = 0;
} completion:^(BOOL finished){
[toVC didMoveToParentViewController:fromVC];
}];
}
else
{
//Dismiss
}
}
这是我的FirstVC.m:
- (void)prepareForSegue:(MyCustomSegue *)segue sender:(id)sender
{
segue.isPresenting = YES;
}
- (UIViewController *)viewControllerForUnwindSegueAction:(SEL)action fromViewController:(UIViewController *)fromViewController withSender:(id)sender
{
return self;
}
- (UIStoryboardSegue *)segueForUnwindingToViewController:(UIViewController *)toViewController fromViewController:(UIViewController *)fromViewController identifier:(NSString *)identifier
{
return [[MyCustomSegue alloc] initWithIdentifier:identifier source:fromViewController destination:toViewController];
}
- (IBAction)unwindToFirstVC:(UIStoryboardSegue *)segue
{
NSLog(@"I am here");
}
所有必要的连接也在故事板中完成。
我的问题是-segueForUnwindingToViewController:
从未被调用。只要返回-viewControllerForUnwindSegueAction:fromViewController:withSender:
,我的程序就会崩溃,并出现以下异常:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not find a view controller to execute unwinding for <FirstViewController: 0x8e8d560>'
根据我的理解,崩溃的原因是,我希望我的容器视图控制器是处理unwind segue动作的那个,这是不可能的(因为容器视图控制器只要求它的子处理unwind segue。
正确吗?我能做些什么来解决我的问题?
谢谢!
我不认为你可以这样使用unwind segue(至少我找不到方法)。相反,你可以创建另一个从子控制器返回到父控制器的"普通"segue,并将其类型设置为custom,使用与从第一个控制器到第二个控制器相同的类。在第二个控制器的prepareForSegue中,将isPresenting设置为NO,并在你的自定义segue
中加入这段代码- (void)perform {
if (_isPresenting) {
NSLog(@"Presenting");
ViewController *fromVC = self.sourceViewController;
SecondVC *toVC = self.destinationViewController;
toVC.view.alpha = 0;
[fromVC addChildViewController:toVC];
[fromVC.view addSubview:toVC.view];
[UIView animateWithDuration:1.0 animations:^{
toVC.view.alpha = 1;
} completion:^(BOOL finished){
[toVC didMoveToParentViewController:fromVC];
}];
}else{
NSLog(@"dismissing");
SecondVC *fromVC = self.sourceViewController;
[fromVC willMoveToParentViewController:nil];
[UIView animateWithDuration:1.0 animations:^{
fromVC.view.alpha = 0;
} completion:^(BOOL finished) {
[fromVC removeFromParentViewController];
}];
}
}
如果你想从SecondVC返回到FirstVC,然后尝试使用这段代码,你告诉你的控制器返回到以前的控制器。
[self dismissViewControllerAnimated:YES completion:nil];
这将工作,你不需要展开代码。