我终于找到了解决问题的方法
首先,我向 View2 添加了一个静态变量,并将其命名为 inView2,如下所示
在 View2.h
@interface
{}
+ ( BOOL ) isInQuizViewController;
+ ( void )setInQuizViewController:(BOOL)inQuizVal;
//...
@end
在 View2.m 中
@implementation
static BOOL inView2 = NO;
+(BOOL)isInView2
{
return inView2;
}
+ ( void )setInView2:(BOOL)Val
{
inView2 = val;
}
这两种方法用于设置和获取 inView2 的值,它告诉我用户当前是否在 View2 中
在 View1.h 中创建一个与按钮关联的 IBAction,该按钮将从 View1 传输到 View2 并将其连接到您的故事板
- (IBAction)GoToView2:(id)sender;
转到 View1.m 并导入
#import "View2.h"
并实现您的 IBAction 方法以将 InView2 设置为 YES
- (IBAction)GoToView2:(id)sender {
[View2 setInView2:YES];
}
然后在delegate.m中
#import "View2.h"
@implementation AppDelegate
UITabBarController * _tabBarController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
_tabBarController = (UITabBarController *)_window.rootViewController;
_tabBarController.delegate = self;
// Override point for customization after application launch.
return YES;
}
我定义了一个全局 _tabBarController 并将其设置为 _window.rootViewController 并将其委托设置为此委托并记住导入“View2.h”
转到 ShouldSelectViewController 方法(请注意,此方法在在过渡到所选选项卡 ViewController 之前调用,因此它非常适合决定是否应将所选选项卡 viewController 显示到用户)。
所以在 ShouldSelectViewController 方法中我做了以下
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
if(tabBarController.selectedIndex == 2)
{
if ([View2 isInView2]) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"alert"
message:@"are you sure you want to exit?"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Yes",nil];
[alertView show];
return NO;
}
}
return YES;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 1)
{//ok button pressed
// NSInteger destinationTabIdx = 2;
// UIView * fromView = tabBarController.selectedViewController.view;
// UIView * toView = [[[[[tabBarController.viewControllers objectAtIndex:destinationTabIdx] navigationController] viewControllers] objectAtIndex:0] view];
UINavigationController *nav = (UINavigationController *)_tabBarController.selectedViewController;
NSLog(@"vc title: %@",nav.title);
// [UIView transitionFromView:fromView toView:toView duration:0.8
// options: UIViewAnimationOptionTransitionNone
// completion:^(BOOL finished) {
// if (finished) {
// tabBarController.selectedIndex = destinationTabIdx;
// }
// }];
[nav popViewControllerAnimated:YES];
[QuizViewController setInQuizViewController:NO];
NSLog(@"app delegate transistion done");
}
}