App Delegate Class 中的选项卡索引正确但在 App Delegate 对象中不正确

Tab Index Correct in App Delegate Class but Not in App Delegate object

我有一个基于选项卡的应用程序。其中一个选项卡是相机。当用户选择取消时,我希望应用程序 return 到它之前所在的选项卡。我通过在我的应用程序委托 class 中保存以前的选项卡索引来做到这一点。在我的应用委托 class 的 shouldSelectViewController 中,它记录了正确的索引。但是,在我的相机class中,它总是说之前的索引是0

    @interface LeafletAppDelegate : NSObject <UIApplicationDelegate, UIAlertViewDelegate, UITabBarDelegate> {

        NSManagedObjectModel *managedObjectModel;
        NSManagedObjectContext *managedObjectContext;       
        NSPersistentStoreCoordinator *persistentStoreCoordinator;
        UIWindow *window;

    }

    @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
    @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
    @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
    @property (strong, nonatomic) UITabBarController *tabBarController;
    @property (nonatomic, assign) NSUInteger previousTabIndex;

//Appdelegate.m 
#import "CameraViewController.m"
#pragma mark UITabBarController Delegate Methods
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    self.previousTabIndex = tabBarController.selectedIndex;
    NSLog(@"this is previous tab index: %lu", (unsigned long)self.previousTabIndex);
    return YES;
}


//CameraViewController.m 
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
    LeafletAppDelegate *appDelegate = (LeafletAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSLog(@"previous tab index: %lu", (unsigned long)appDelegate.previousTabIndex);
    [self.tabBarController setSelectedIndex:appDelegate.previousTabIndex];
}

为什么它会在我的应用委托 class 中打印正确的索引,但当我在我的相机 [=20= 的应用委托对象中访问 属性 时却没有]?

不要为此使用 AppDelegate。正如 class 名称所说,它仅用于应用程序委托。

你必须从 UITabBarController 创建一个子 class,例如:

 @interface LeafletTabBarController : UITabBarController <UITabBarControllerDelegate>

注意这个class正在实现UITabBarControllerDelegate,所以你需要在viewDidLoad里面设置self.delegate = self

其他,在此子 class 中,您可以创建 属性 @property (nonatomic) NSUInteger previousTabIndex 并在视图控制器内创建取消操作:

LeafletTabBarController *tabBarController = (LeafletTabBarController*)self.tabBarController;
        [tabBarController tabBar:tabBarController.tabBar didSelectItem:tabBarController.tabBar.items[tabBarController.previousTabIndex]];

不要忘记设置您当前的标签栏 class,并且不要忘记在您的 LeafletTabBarController - (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController 中更新 previousTabIndex;

希望对您有所帮助!