How to change UIBarButtonItem's type in UINaviagationBar at runtime?

人盡茶涼 提交于 2019-12-05 04:21:09

There is a builtin bar button with this behaviour, you get it via the editButtonItem property of a UIViewContoller. Tabbing that button will change the view controller it came from into editing mode, and toggle the button into a done button.

- (void)viewDidLoad {
  [super viewDidLoad];
  self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
GregLBS

If you have added the button through IB then make sure to set the identifier to Custom Also allocate a button in the .h with appropriate IBOutlet and Property Synthesize the button in .m

Then in your code do the following:

// Set to done
editButton.style = UIBarButtonItemStyleDone;
editButton.title = @"Done";

// Set back to edit
editButton.style = UIBarButtonItemStyleBordered;
editButton.title = @"Edit";

to change the button the Done button use this

[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleDone];

to change the button to Edit button use this

[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleBordered];

I ended up doing something like this. Unfortunately, setting the title directly did not work, for some reason it was nil and would not let me set it to a different value. The self.editButton comes from an IBOutlet with the target and actions set. This code uses ARC. I hope this helps someone.

        NSString *title = app.settings.editing 
                        ? NSLocalizedString(@"Done", @"")
                        : NSLocalizedString(@"Edit", @"");

        UIBarButtonItemStyle style  = app.settings.editing 
                                    ? UIBarButtonItemStyleDone
                                    : UIBarButtonItemStyleBordered;

        UIBarButtonItem *editButton 
            = [[UIBarButtonItem alloc] initWithTitle:title 
                                               style:style 
                                              target:self.editButton.target 
                                              action:self.editButton.action];

        self.navigationItem.rightBarButtonItem = editButton;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!