I'm trying to set up a list of items that can be edited. I have a main view, with a UINavigationBar at the top and a UITableView directly under it. I'd like to have my "edit" button change to a "done" button on click, but I can't figure out how to do it.
If I could do it in the code (not it interface builder), I could just replace it, but I can't even do that. I've seen some code using [self.navigationItem], but in my case self is a UIView.
It also feels a bit odd to be using a UINavigationBar when I don't want navigation (this is one page only), but I want a toolbar with a title and and a button, so I don't think really have a choice.
I create one button that can change from Edit to Done. It's a tip from More iPhone Development book.
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *editButton = self.editButtonItem;
[editButton setTarget:self];
[editButton setAction:@selector(toggleEdit)];
self.navigationItem.leftBarButtonItem = editButton;
}
And the method toggleEdit
- (IBAction)toggleEdit {
BOOL editing = !self.tableView.editing;
self.navigationItem.rightBarButtonItem.enabled = !editing;
if (editing) {
self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"Done", @"Done");
//Added in the edition for this button has the same color of the UIBarButtonSystemItemDone
self.navigationItem.leftBarButtonItem.style = UIBarButtonItemStyleDone;
} else {
self.navigationItem.leftBarButtonItem.title = NSLocalizedString(@"Edit", @"Edit");
//Added in the edition for this button has the same color of the UIBarButtonSystemItemDone
self.navigationItem.leftBarButtonItem.style = UIBarButtonItemStylePlain;
}
[self.tableView setEditing:editing animated:YES];
}
Then you don't need replace any of them.
When you use self.editButtonItem
, you don't need to change the style and text of the button, it is done automatically. Try removing that code, it will still work :)
set up nav button in IB with the following linked in IB and create an outlet called editOutlet and and an action called editToggle in your header file and your method is as easy as this:
-(IBAction) editToggle:(id) sender {
if (self.tableViewOutlet.isEditing == NO) {
self.editOutlet.title = NSLocalizedString(@"Done", @"Done");
self.editOutlet.style = UIBarButtonItemStyleDone;
[self.tableViewOutlet setEditing:YES animated:YES];
}else {
self.editOutlet.title = NSLocalizedString(@"Edit", @"Edit");
self.editOutlet.style = UIBarButtonItemStylePlain;
[self.tableViewOutlet setEditing:NO animated:YES];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With