选项卡索引在App Delegate类中更正,但不在App Delegate对象中

时间:2018-02-03 00:38:43

标签: ios objective-c uitabbarcontroller uiimagepickercontroller

我有一个基于标签的应用程序。其中一个标签是相机。当用户选择取消时,我希望应用程序返回之前的选项卡。我这样做是通过在我的应用委托类中保存以前的选项卡索引。在我的app委托类的shouldSelectViewController中,它会记录正确的索引。但是,在我的相机类中,它总是说前一个索引是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];
}

为什么它会在我的app委托类中打印正确的索引,但是当我在相机类的app delegate对象中访问该属性时却不能?

1 个答案:

答案 0 :(得分:2)

不要使用AppDelegate。正如类名所示,它仅适用于应用程序委派。

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

 @interface LeafletTabBarController : UITabBarController <UITabBarControllerDelegate>

请注意,此类正在实现UITabBarControllerDelegate,因此您需要在self.delegate = self内设置viewDidLoad

另外,在这个子类中,您可以在视图控制器中创建属性@property (nonatomic) NSUInteger previousTabIndex和取消操作:

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

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

希望它有所帮助!

相关问题