我有一个UINavigationGroup
,其根视图控制器名为MainViewController
。在MainViewController
内,我将另一个UINavigationController
称为模式,如下所示:
- (IBAction)didTapButton:(id)sender {
UINavigationController * someViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"someNavigationController"];
[self.navigationController presentViewController:someViewController animated:YES completion:nil];
}
在这个someNavigationController
中,用户正在经历一些过程,因此导航控制器被推送了一些UIViewControllers
。在用户完成此过程后,在最后一个名为UIViewController
的{{1}}中,我正在关闭模式,如下所示:
finalStepViewController
模态确实被驳回,用户又回到了最初的[self dismissViewControllerAnimated:YES completion:nil];
。
但是,我想将另一个MainViewController
推送到UIViewController
的NavigationController(例如:一个说明用户已成功完成该过程的视图)。最好在模态被解散之前。
我尝试了以下事项:
1。使用MainViewController
presentingViewController
结果:没有错误,但也没有发生任何事情。
2。委托/协议
UIViewController * successViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"successViewController"];
[self.presentingViewController.navigationController successViewController animated:YES];
内导入finalStepViewController.h
并附加MainViewController.h
<finalStepViewControllerDelegate>
内添加了一个名为MainViewController.m
的方法,可以从parentMethodThatChildCanCall
在finalStepViewController.m
中添加了以下内容:
finalStepViewController.h
@protocol finalStepViewControllerDelegate <NSObject>
-(void)parentMethodThatChildCanCall;
@end
和模型中的@property (assign) id <finalStepViewControllerDelegate> delegate;
@synthesize delegate;
IBAction中的委托属性设置为someViewController
为self。这显示了一条通知错误:didTapButton
Assigning to id<UINavigationControllerDelegate>' from incompatible type UIViewController *const __strong'
。结果:除了通知错误之外,没有失败但没有任何反应,因为[self.delegate parentMethodThatChildCanCall]
未被调用。
知道我做错了什么/我应该做什么?这是我第二周做Objective-C,大部分时间我都不知道我在做什么,所以任何帮助/代码都会受到赞赏!
感谢。
答案 0 :(得分:1)
使用NSNotificationCenter
可以轻松实现这一目标。
在MainViewController
的{{1}}中添加以下代码
-viewDidLoad
在dealloc
上从NSNotificationCenter中删除您的控制器 typeof(self) __weak wself = self;
[[NSNotificationCenter defaultCenter] addObserverForName:@"successfullActionName"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
SuccessViewController *viewController; // instantiate it properly
[wself.navigationController pushViewController:viewController animated:NO];
}];
在- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
关于在解除通知之前解除视图控制器的操作
FinalStepViewController
此示例非常粗糙且不理想,您应该使用常量作为通知名称,并在某些情况下存储- (IBAction)buttonTapped:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"successfullActionName" object:nil];
[self dismissViewControllerAnimated:YES completion:nil];
}
返回的观察者以删除特定的观察者。
- 编辑
我还想提一下,方法NSNotificationCenter
实际上将观察者作为addObserverForName:object:queue:usingBlock:
类型对象返回。您需要在类中将对它的引用存储为iVar,并在调用id
方法时将其从NSNotificationCenter
中删除,否则观察者将永远不会被释放。