iOS didSelectTabBarItem知道之前选择了什么项目

Spe*_*pgh 3 iphone uitabbaritem uitabbar ios

我有一个带有a的IOS应用程序,UITabBar并将其委托设置为我的班级.. didSelectTabBarItem适当的火灾,一切都是对的世界.但是我确实有一些条件代码必须在UITabBarItem选定的是在一个特定的UITabBarItemIE 之后发生..如果用户点击标签栏项目3,并且它们当前在标签栏项目2上我必须做一些额外的代码,如果用户选择了标签栏项目3并且之前在标签栏项目1上,则不必执行此操作.

那么,无论如何都是以编程方式(除了通过状态变量通过我的程序保持直接跟踪,以便在选择新的标签栏项目时知道标签栏上的先前选择的项目是什么?

NJo*_*nes 5

是的,通过键值观察(KVO)是可能的.

注意这个答案是关于a UITabBar而不是a UITabBarController.标签栏控制器委托具有您正在寻找的方法(如rdelmar所述).

首先,请观察您的标签栏,如下所示:

- (void)viewDidLoad{
    [super viewDidLoad];
    [self.tabBar addObserver:self forKeyPath:@"selectedItem" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
}
Run Code Online (Sandbox Code Playgroud)

我认为你已经可以根据我使用的旧选项和新选项看到我要去的地方了.然后只需观察更改而不是使用委托方法,如下所示:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"selectedItem"] && [object isKindOfClass:[UITabBar class]]){
        UITabBar *bar = (UITabBar *)object; // The object will be the bar we're observing.
        // The change dictionary will contain the previous tabBarItem for the "old" key.
        UITabBarItem *wasItem = [change objectForKey:NSKeyValueChangeOldKey];
        NSUInteger was = [bar.items indexOfObject:wasItem];
        // The same is true for the new tabBarItem but it will be under the "new" key.
        UITabBarItem *isItem = [change objectForKey:NSKeyValueChangeNewKey];
        NSUInteger is = [bar.items indexOfObject:isItem];
        NSLog(@"was tab %i",was);
        NSLog(@"is tab  %i",is);
    } 
    // handle other observings.
}
Run Code Online (Sandbox Code Playgroud)

记得删除自己在这两个观察员viewDidUnloaddealloc,因为viewDidUnload可能永远不会被调用.