0

我有一个在情节提要中内置的 viewController。我还有一个 NSObject 子类,它充当我的模型,它发送和侦听 API 请求和响应。当一个方法在我的模型中触发时,我想从当时碰巧可见的任何视图中呈现我的 viewController 的模态视图。

一个例子是,如果我的 API 听到“显示此视图”,我想显示 viewController,而不管显示的是什么视图。

从概念上讲,如何做到这一点?

编辑:当我想展示我的模态视图控制器时,我不知道将显示哪个视图控制器。此外,当它出现时,我需要将参数从我的模型传递给 modalVC。

4

2 回答 2

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"];

通过这种方式,您的模型与演示文稿分离。

于 2012-09-11T20:33:38.567 回答
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;
}
于 2012-09-11T20:26:14.047 回答