当我按下公共自定义视图中的按钮时,我想推送视图控制器,该按钮作为mainviewcontoller
中的子视图添加。该方法应该在单例类中,以便在所有类中都有这个方法,如何做到这一点请建议我?
是否可以在singleton类中使用该方法?
CreateContactViewController *contactList = [self.storyboard instantiateViewControllerWithIdentifier:@"createContact"];
[self.navigationController pushViewController:contactList animated:YES];
答案 0 :(得分:1)
您应该获得可见视图控制器的UINavigationController实例并在其上推送视图控制器。
- (void)foo
{
UIViewController *rootVC = [[UIApplication sharedApplication].keyWindow.rootViewController;
UINavigationController *nc = [self topViewControllerWithRootViewController:rootVC].navigationController;
if (nc) {
CreateContactViewController *contactList = [nc.storyboard instantiateViewControllerWithIdentifier:@"createContact"];
[nc pushViewController:contactList animated:YES];
} else {
// Here is the case when the visible view controller is presented modally and not embedded in UINavigationController.
// So here you can ONLY present your new view controller modally.
// Or dismiss the modally presented one and then push your new view controller
}
}
- (UIViewController*)topViewControllerWithRootViewController: (UIViewController*)rootViewController
{
if ([rootViewController isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabBarController = (UITabBarController*)rootViewController;
return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
} else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
UINavigationController* navigationController = (UINavigationController*)rootViewController;
return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
} else if (rootViewController.presentedViewController) {
UIViewController* presentedViewController = rootViewController.presentedViewController;
return [self topViewControllerWithRootViewController:presentedViewController];
} else {
return rootViewController;
}
}