UITabBar can't change selected index

2019-08-09 15:09发布

问题:

I'm having trouble changing the index of my UITabBar. I am attempting to change it from the UITabBarController subclass. This is what I'm trying:

[self.tabBarController setSelectedIndex:1];

This is what my .h looks like

#import <UIKit/UIKit.h>

@interface CustomTab : UITabBarController <UITabBarControllerDelegate>{
     IBOutlet CustomTab *bar;
}

@end

I am trying to set the index with an IBAction, the method is being called, but the index doesn't change. Any ideas?

回答1:

Because you are calling

[self.tabBarController setSelectedIndex:1];

from inside the CustomTab class itself. You need to replace it with

[self setSelectedIndex:1];


回答2:

for swift

override func viewWillAppear(_ animated: Bool) {
    self .selectedIndex = 3 // desired index
}