关于initWithNavigationBarClass的困惑 – 如何使用(new instanceType方法)

这很好用:

UINavigationController *nc = [[UINavigationController alloc] initWithNavigationBarClass:[GTScrollNavigationBar class] toolbarClass:[UIToolbar class]]; nc.viewControllers = @[firstPage]; self.window.rootViewController = nc; 

但是这不起作用:

 UINavigationController *nc = [[UINavigationController alloc] initWithNavigationBarClass:[GTScrollNavigationBar class] toolbarClass:[UIToolbar class]]; self.window.rootViewController = nc; self.window.rootViewController.viewControllers = @[firstPage]; // ERROR 

怎么会这样? 谢谢

 self.window.rootViewController.viewControllers = @[firstPage]; 

不会编译,因为UIWindowrootViewController属性被声明为(通用) UIViewController (它没有viewControllers属性),而不是作为UINavigationController

编译器不会“知道”根视图控制器实际上是您的情况下的导航控制器。

所以要么像你的第一个代码块那样继续,要么你必须添加一个明确的强制转换:

 ((UINavigationController *)self.window.rootViewController).viewControllers = @[firstPage];