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

独自空忆成欢 提交于 2019-12-07 02:48:13

问题


I am working on an iPhone's view which composed 3 elements, UITextView, UIToolBar with an UIBarButtonItem.

The goal is, I want UIBarButtonItem change its style from 'edit' (UIBarButtonSystemItemEdit) to 'Done' (UIBarButtonSystemItemDone) and update new selector to new method.

First of all, I have tried following code but it doesn't work:

Could you help me on this idea?


回答1:


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;
}



回答2:


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";



回答3:


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];



回答4:


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;


来源:https://stackoverflow.com/questions/1648244/how-to-change-uibarbuttonitems-type-in-uinaviagationbar-at-runtime

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