Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView Edit/Done Button

How can I implement a button on the navigation bar whereby the user would be able to reorder & delete rows of a UITableView?

Do I have to create my own toolbar button to have the Edit/Done button for my UITableView?

like image 352
Gavin Avatar asked Sep 12 '11 09:09

Gavin


3 Answers

Just add this line in viewDidLoad of your UITableViewController

self.navigationItem.leftBarButtonItem = self.editButtonItem;

It will work if your table view superview is UINavigationController. This line will add button that will push table in edit mode and out of it.

like image 164
Nekto Avatar answered Oct 21 '22 08:10

Nekto


What's generally done is you create your own custom BarbuttonItem and then assign this button as right navigation bar button item:

UIBarButtonItem *barButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"Edit"
                                                               style:UIBarButtonItemStylePlain
                                                              target:self 
                                                              action:@selector(toggleEdit)];

self.navigationItem.rightBarButtonItem = barButtonItem;   
[barButtonItem release];

Here's the toggleEdit method:

-(void)toggleEdit{
          [self.tableView setEditing:!self.tableView.editing animated:YES]; 

          if (self.tableView.editing) 
              [self.navigationItem.rightBarButtonItem setTitle:@"Done"]; 
          else 
             [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];  
}
like image 45
Mikayil Abdullayev Avatar answered Oct 21 '22 08:10

Mikayil Abdullayev


UIButton *btnname=[UIButton buttonWithType:UIButtonTypeSystem];
[btnname setFrame:CGRectMake(0,0,110,35)];
[btnname setFont:[UIFont boldSystemFontOfSize:18]];
[btnname setTitle: @"Delete" forState: UIControlStateNormal];
[btnname setTitleColor:UIColorFromRGB(0xCC0707)        forState:UIControlStateNormal];
btnname.backgroundColor=UIColorFromRGB(0xE6E7E8);
btnname.showsTouchWhenHighlighted = YES;
[btnname addTarget:self
            action:@selector(toggleEdit)
forControlEvents:UIControlEventTouchDown];
UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:btnname];
self.navigationItem.rightBarButtonItem = barItem;


-(void)toggleEdit{
    [self.tableView setEditing:!self.tableView.editing animated:YES];

    if (self.tableView.editing)
         [btnname setTitle: @"Done" forState: UIControlStateNormal];
    else
         [btnname setTitle: @"Delete" forState: UIControlStateNormal];
}
like image 25
Saravanan Avatar answered Oct 21 '22 09:10

Saravanan