UIBarButtonItem 上按钮切换/隐藏的简单例子 转载

Posted on 2014-04-26 11:58  郑博文  阅读(1159)  评论(0编辑  收藏  举报

    首先我先说一下demo的背景:

    导航条右侧有个edit button, 中间是title ,左边是back button 和 add button。代码实现是:点击edit button时,back button隐藏 同时显示add button。用户点击 done button时则显示

back button 同时隐藏add button。

    代码实现:

 1 - (void)viewDidLoad {
 2       [super viewDidLoad];
 3       self.navigationItem.rightBarButtonItem = self.editButtonItem;
 4 }

// 点击Edit按钮设置是否显示一个可编辑视图的视图控制器

// 用户不重写该方法时 即使self.navigationItem.rightBarButtonItem = self.editButtonItem了,Edit也无法触发编辑状态

// 用户重新写该方法时,点击Edit按钮 editing为YES 触发编辑状态 而animated始终为YES 在编写时必须调用父类方法。用户点击Done按钮 editing为No 退出编辑状态

 5 - (void)setEditing:(BOOL)editing animated:(BOOL)animated {
 6     [super setEditing:editing animated:animated];
 7     [self.navigationItem setHidesBackButton:editing animated:YES];
 8     if (editing) {
 9             self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]           initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self  action:@selector(insertMe)] autorelease];
10 }else {
11       self.navigationItem.leftBarButtonItem = nil;
12       //self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self  action:@selector(backButton) ] autorelease];
13 }
14 }

其中 back button 是系统默认的,去掉 else 里面的注释,就可以加入其他按钮。  

Copyright © 2024 郑博文
Powered by .NET 8.0 on Kubernetes