Ios 如何获取选定的选项卡栏项?

Ios 如何获取选定的选项卡栏项?,ios,Ios,我仔细研究了一些问题,发现: NSLog(@"selected tab index => %d",self.tabBarController.tabBar.selectedItem.tag); 但是,这总是返回0。 我做错了什么 AppDelegate中的我的代码: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

我仔细研究了一些问题,发现:

NSLog(@"selected tab index => %d",self.tabBarController.tabBar.selectedItem.tag);
但是,这总是返回0。 我做错了什么

AppDelegate中的我的代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    // Assign tab bar item with titles
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    UITabBar *tabBar = tabBarController.tabBar;
    UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
    UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
    UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];    
    return YES;
}
编辑:

我想这样做:

if(self.tabBarController.tabBar.selectedItem.tag == 0)
{
    [[UITabBar appearance] setSelectedImageTintColor:[UIColor orangeColor]];
}   
else     if(self.tabBarController.tabBar.selectedItem.tag == 1)
{
    [[UITabBar appearance] setSelectedImageTintColor:[UIColor blueColor]];
}   

您必须在序列图像板编辑器中或以编程方式将标记值指定给该项,使其不同于零。

让我们试试:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
NSLog(@"%d",tabBarController.selectedIndex); //2147483647, will return tab 0
tabBarController.selectedIndex = 1;
NSLog(@"%d",tabBarController.selectedIndex); // will return 1
return YES;
}
要获得它:

//my comment : be sure that self.tabBarController is tabBarController from your appDelegate
if(self.tabBarController.selectedIndex == 0)
{
[[UITabBar appearance] setSelectedImageTintColor:[UIColor orangeColor]];
}   
else if(self.tabBarController.selectedIndex == 1)
{
[[UITabBar appearance] setSelectedImageTintColor:[UIColor blueColor]];
}   

你应该在故事板部分解决这个问题。选择UITabBarItem并转到其属性。转到选项“标记”并设置值(默认情况下,所有值都设置为0)

原始问题询问如何使用标记获取/设置UItabaritem。我看不到一个真正的答案

标签是一个更好的值,尤其是如果您希望保存或“记住”该值,以便能够在将来的会话中恢复“最后一次”选择的标签,则可以使用该值。如果用户从更多菜单重新排列选项卡,则选项卡栏上任何viewController的索引都可能更改,而如果应用程序设计正确,则标记不会更改

要获取当前选定TabBarItem的标记,请执行以下操作:

_tabBarController.tabBar.selectedItem.tag;
要从值还原/设置它,请执行以下操作:

unsigned lastSelectedIndex = [[userSettings objectForKey:SavedTabLastViewedKey] unsignedIntValue];
for(UIViewController *vc in _tabBarController.viewControllers) {
    if(vc.tabBarItem.tag == lastSelectedIndex) {
        _tabBarController.selectedViewController = vc;
        break;
    }
}

使用
self.tabBarController.selectedIndex
,它将给出与当前所选选项卡项关联的视图控制器的索引。您的选项卡中是否有导航控制器?否我使用的选项卡栏控制器与模板项目中的一样(基于选项卡的应用程序)我确实没有,但是我仍然无法获取所选选项卡。这将设置我想要获取的selectedIndex。所以如果你按下第一个标签,我想得到0,第二个标签1等等,这样我就可以使用if语句,比如if(selectedIndex==0){//do something}