我有一个自定义按钮,我想添加到导航栏上。到目前为止,这就是我的 RootViewController
中的内容(它继承了 UIViewController
,UINavigationController
是通过 AppDelegate
添加的):
在viewDidLoad
中:
UIBarButtonItem *share = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon"] style:UIBarButtonItemStylePlain target:self action:@selector(share:)];
self.navigationController.navigationItem.rightBarButtonItem = share;
以下是我的 UINavigationController
的设置方式:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
UIViewController *rootViewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
[navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbar"] forBarMetrics:UIBarMetricsDefault];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
return YES;
}
为什么这不起作用?
编辑:
在我将 self.navigationController.navigationItem.rightBarButtonItem
替换为 self.navigationItem.rightBarButtonItem
后,它就起作用了。这是为什么?我的 rootviewcontroller 是 UIViewController
类型,我应该通过 navigationController
访问 navigationItems
。在这种情况下,navigationController
是什么?
最佳答案
It worked after I replaced self.navigationController.navigationItem.rightBarButtonItem with self.navigationItem.rightBarButtonItem. Why is that?
UIViewController 的每个实例都有一个 navigationItem。这包括 UINavigationController,它是 UIViewController 的子类。
当新的 View Controller 出现时,UINavigationController 使用 navigationItem 来更新其视觉状态。当您修改 self.navigationController.navigationItem 时,您正在修改嵌套 UINavigationController 时显示的内容。实际上,您永远不会修改 UINavigationController 的 navigationItem,因为您不会有嵌套的导航 Controller 。
正如您所发现的,您必须修改 View Controller 的 navigationItem
才能使更改在导航 Controller 中生效。
What is navigationController in this case?
navigationController
是对 UINavigationController 的引用,self
表示的 View Controller 当前包含在该 UINavigationController 中。
例如:
UIViewController* viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:viewController];
// This is TRUE: viewController.navigationController == navController
关于iphone - 自定义 UIBarButtonItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11004801/