場景模擬:
點(diǎn)擊一個(gè)按鈕,彈出一個(gè)導(dǎo)航視圖。導(dǎo)航視圖中包含左按鈕:取消按鈕魔策;右按鈕:存儲(chǔ)信息(什么亂起八糟的隨你)出現(xiàn)問題:
為導(dǎo)航視圖設(shè)置導(dǎo)航欄的左右按鈕后不顯示。
有一個(gè)UIViewController 和一個(gè)UINavigationController:
UIViewController* controller = [[UIViewController alloc]init];
UINavigationController* navigationController = [[UINavigationController alloc]initWithRootViewController:controller];
設(shè)置導(dǎo)航欄的左右按鈕:
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;
展現(xiàn)該導(dǎo)航視圖:
[self presentViewController:navigationController animated:YES completion:nil];
發(fā)現(xiàn)導(dǎo)航視圖并不現(xiàn)實(shí)左右按鈕河胎,command+點(diǎn)擊 進(jìn)入navigationItem查看其聲明和注釋:
@property(nonatomic,readonly,strong) UINavigationItem *navigationItem; // Created on-demand so that a view controller may customize its navigation appearance.```
大概意思是:在程序有需要時(shí)才創(chuàng)建闯袒,若有一個(gè)viewcontroller則可能屏蔽當(dāng)前navigation中的item
* 解決方案:
將
` navigationController.navigationItem.leftBarButtonItem=leftButtonItem; navigationController.navigationItem.rightBarButtonItem=rightButtonItem;`
改為:
`
controller.navigationItem.leftBarButtonItem=leftButtonItem;
controller.navigationItem.rightBarButtonItem=rightButtonItem;
`
即可(本人不準(zhǔn)確地理解為:UINavigationController并不具有view,因此需要擁有rootViewController即UIViewController,因此其外觀也被UIViewController所決定游岳,所以需要設(shè)置UIViewController來設(shè)置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");
}
運(yùn)行截圖:
](http://upload-images.jianshu.io/upload_images/2920598-407c584f1e8b4449.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)