当前视图控制器被解除时(popped或dismissModalDialog'd),是否有通知的最佳实践方式?我不能使用-viewWillDisappear :,因为当另一个viewController被推到当前的那个时,它也会被调用。
答案 0 :(得分:11)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
[self addObserver:self forKeyPath:@"parentViewController" options:0 context:NULL];
}
return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([@"parentViewController" isEqualToString:keyPath] && object == self) {
if (!self.parentViewController)
NSLog(@"Dismissed");
}
}
- (void)dealloc
{
[self removeObserver:self forKeyPath:@"parentViewController"];
[super dealloc];
}
答案 1 :(得分:0)
据我所知,没有自动获取通知的方法,但由于UIViewController有一个modalViewController属性,你可以定义类似“didDismiss ...”,并在呈现你的新模式后调用上一个模态视图控制器上的方法模态视图控制器。
答案 2 :(得分:0)
你能澄清一下你的问题吗?
我在想你在问:
ViewcontrollerONE以模态方式弹出ViewControllerTWO。 ViewControllerTWO被解雇。 ViewControllerONE想要知道那个ViewControllerTWO只是解散了自己,并且想要运行XYZ方法。
我没有一个好的答案,但我确实有办法:
在VC2中简单引用VC1。所以VC2可以在解雇前通知VC1。
答案 3 :(得分:0)
使用KVO的所选答案在iOS 8上对我不起作用。
我将UIViewController子类化为如下,然后我只在所呈现的视图控制器上调用dismissAnimated:completion:
而不是dismissViewControllerAnimated:completion:
。我注册在其他地方观察通知并根据需要触发处理。
#define DismissNotifyViewControllerDismissedNotification @"DismissNotifyViewControllerDismissed"
@interface DismissNotifyViewController : UIViewController
- (void)dismissAnimated:(BOOL)flag completion:(void (^)(void))completion;
@end
@implementation DismissNotifyViewController
- (void)dismissAnimated:(BOOL)flag completion:(void (^)(void))completion
{
[self.presentingViewController dismissViewControllerAnimated: flag
completion: ^{
if (completion)
completion();
[NSNotificationCenter.defaultCenter
postNotificationName: DismissNotifyViewControllerDismissedNotification
object: self];
}];
}
@end
答案 4 :(得分:0)
Apple更改了iOS8中的演示文稿,他们正在使用presentationControllers,因为presentationControllers不是KVO compilant,我必须使用containerView
,因为它是removedFromSuperview
并且-[UIPresentationController transitionDidFinish:]
时是n {调用。适用于iOS8及以上版本的解决方案:
self.presentationContext.presentViewController(self.viewControllerToPresent, animated: true, completion: { _ in
self.viewControllerToPresent.presentationController?.addObserver(self, forKeyPath: "containerView", options: [], context: &self.observingContext)
})
我添加观察者是completionHandler,因为演示文稿有时会失败,尤其是在呈现已经呈现的viewController时。
在观察者值中,我必须在containerView不再存在时删除观察:
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard &self.observingContext == context else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
return
}
if let presentationController = object as? UIPresentationController where presentationController.containerView == nil {
presentationController.removeObserver(self, forKeyPath: "containerView")
}
}