首页 文章

从UIVIewController访问UITabBarController

提问于
浏览
18

我正在开发基于UITabbar和视图层次结构的应用程序,如下所示 .

UITabBarController ----> UINavigationController ----> UIViewController

我需要从UIIVewController访问UITabBarController . 但是以下属性总是返回nil .

self.tabBarController和self.navigationController.tabBarController

有没有办法直接从子viewController访问Tabbarcontroller而不使用AppDelegate?

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"Home";
        self.navigationItem.title = @"Home";

        self.tabBarItem.image = [UIImage imageNamed:@"TabBarHome"];

        UITabBarController *tab = self.tabBarController;
         UITabBarController *tab1 = self.navigationController.tabBarController;
        UITabBarController *tab2 = self.navigationController.presentingViewController;



    }
    return self;
}

2 回答

  • 26

    随着你正在使用的层次结构:

    enter image description here

    我可以在没有问题的情况下从 ViewController 获取 UITabBarController

    self.tabBarController

    将自定义初始化移动到 viewDidLoadviewDidAppear

    然后为shure你可以访问 TabBarControllerself.tabBarController

    到达TabBarController的另一种方法是:

    UITabBarController *tabBarController = (UITabBarController *)[[[UIApplication sharedApplication] delegate] window].rootViewController;
    

    但在你的情况下完全没有必要 .

    EDIT:

    如果您正在使用Xib,那么您已经在AppDelegate中以编程方式创建了一个TabBarController . 我相信你有类似的东西:

    self.tabBarController = [[UITabBarController alloc] init];

    然后你可以在你的ViewController中调用它:

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]
    UITabBarController *tabBarController = appdelegate.tabBarController;
    
  • 4

    你做错了 .

    我有一个与你相同的应用程序 . 我可以从 viewDidLoad 访问tabbar .

    试试这个:

    - (void)viewDidLoad {
        [super viewDidLoad];
        [self.tabBarController setSelectedIndex:1];
    }
    

    希望这可以帮助.. :)

相关问题