gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:09:58 25 4
gpt4 key购买 nike

我有一个带有 UITabBar 的 IOS 应用程序,并将其委托(delegate)设置为我的类。didSelectTabBarItem 正确触发,一切正常。 However I do have some conditional code that has to occur when the UITabBarItem selected is after one particular UITabBarItem IE.. if the user clicks on tab bar item 3, and they were目前在标签栏项目 2 上,我必须做一些额外的代码,如果用户选择标签栏项目 3 并且之前在标签栏项目 1 上,我就不必这样做。

So, is there anyway programmatically (other than keeping direct track via my program via a state variable, to know what was the previously selected item was on a tab bar when a new tab bar item is selected?

最佳答案

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

注意 这个答案是关于 UITabBar 而不是 UITabBarController。选项卡栏 Controller 委托(delegate)具有您正在寻找的方法(如 rdelmar 所述)。

首先,像这样观察你的标签栏:

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

我想您已经可以根据我使用旧选项和新选项看到我要去的地方。然后简单地观察变化而不是使用委托(delegate)方法,像这样:

-(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.
}

请记住在 viewDidUnloaddealloc 中删除自己作为观察者的身份,因为可能永远不会调用 viewDidUnload

关于iphone - iOS didSelectTabBarItem 知道之前选择了什么项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12444361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com