我有一个viewController,我已经在故事板中构建了。我还有一个NSObject子类,它充当我的模型,它发送和侦听API请求和响应。当一个方法在我的模型中触发时,我想从当时可见的任何视图中呈现我的viewController的模态视图。
一个例子是如果我的API听到“显示此视图”我想显示viewController而不管显示的是什么视图。
从概念上讲,如何做到这一点?
编辑:当我想要呈现我的模态viewController时,我不知道将显示哪个视图控制器。此外,我需要将模型中的参数传递给modalVC。
答案 0 :(得分:2)
我会从模型中发送通知,告诉“某人”需要显示某些视图。
NSDictionary *userInfo = @{ @"TheViewKey": viewToDisplay];
[[NSNoticationCenter defaultCenter] postNotificationName:@"NotificationThatThisViewNeedsToBeDisplayed" object:self userInfo:userInfo];
然后在委托(或活动视图控制器)上注册此通知并处理显示。
// self is the delegate and/or the view controller that will receive the notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleViewToDisplay:) name:@"NotificationThatThisViewNeedsToBeDisplayed" object:nil];
如果放入视图控制器,请记得在视图不可见时从观察者中删除self:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"NotificationThatThisViewNeedsToBeDisplayed"];
这样,您的模型就会与演示文稿分离。
答案 1 :(得分:1)
您有当前的viewController(任何viewController子类)使用以下内容呈现新视图:
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion
编辑:要查找顶视图控制器,请向UITabBarController询问selectedViewController(如果使用tabBarController)以获取“种子”,或者从window.rootViewController开始。
一旦你通过任何tabBarControllers,那么你应该只有UIViewController子类和UINavigationControllers。你可以使用这样的循环:
- (UIViewController *)frontmostController:(UIViewController *)seed
{
UIViewController *ret;
if([seed isKindOfClass:[UINavigationController class]]) {
ret = [(UINavigationController *)seed topViewController];
} else
if([seed isKindOfClass:[UIViewController class]]) {
ret = seed.presentedViewController;
}
return ret ? [self frontmostController:ret] : seed;
}