-
场景模拟:
点击一个按钮,弹出一个导航视图。导航视图中包含左按钮:取消按钮;右按钮:存储信息(什么乱起八糟的随你) -
出现问题:
为导航视图设置导航栏的左右按钮后不显示。
有一个UIViewController 和一个UINavigationController:
UIViewController* controller = [[UIViewController alloc]init];
UINavigationController* navigationController = [[UINavigationController alloc]initWithRootViewController:controller];
设置导航栏的左右按钮:
UIBarButtonItem* leftButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(clickCancel)];
UIBarButtonItem* rightButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self
action:@selector(clickSave)];
navigationController.navigationItem.leftBarButtonItem=leftButtonItem; navigationController.navigationItem.rightBarButtonItem=rightButtonItem;
展现该导航视图:
[self presentViewController:navigationController animated:YES completion:nil];
发现导航视图并不现实左右按钮,command+点击 进入navigationItem查看其声明和注释:
@property(nonatomic,readonly,strong) UINavigationItem *navigationItem; // Created on-demand so that a view controller may customize its navigation appearance.```
大概意思是:在程序有需要时才创建,若有一个viewcontroller则可能屏蔽当前navigation中的item
* 解决方案:
将
` navigationController.navigationItem.leftBarButtonItem=leftButtonItem; navigationController.navigationItem.rightBarButtonItem=rightButtonItem;`
改为:
`
controller.navigationItem.leftBarButtonItem=leftButtonItem;
controller.navigationItem.rightBarButtonItem=rightButtonItem;
`
即可(本人不准确地理解为:UINavigationController并不具有view,因此需要拥有rootViewController即UIViewController,因此其外观也被UIViewController所决定,所以需要设置UIViewController来设置NavigationController)。
* 贴上完整代码:
-(IBAction)click:(id)sender {
UIViewController* controller = [[UIViewController alloc]init];
UINavigationController* navigationController = [[UINavigationController alloc]initWithRootViewController:controller];
UIBarButtonItem* leftButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(clickCancel)];
UIBarButtonItem* rightButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self
action:@selector(clickSave)];
controller.title=@"damn";
controller.navigationItem.leftBarButtonItem=leftButtonItem;
controller.navigationItem.rightBarButtonItem=rightButtonItem;
[navigationController.view setBackgroundColor:[UIColor whiteColor]];
[self presentViewController:navigationController animated:YES completion:nil];
}
-(void)clickCancel{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)clickSave{
NSLog(@"save successfully");
}
运行截图:
![
![2.png](https://img.haomeiwen.com/i2920598/43d6d75dda8354cb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)](https://img.haomeiwen.com/i2920598/407c584f1e8b4449.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
网友评论