iPhone, hook for edit/done button click in table view

后端 未结 4 1581
说谎
说谎 2021-02-01 17:54

In my table view controller there is

self.navigationItem.leftBarButtonItem = self.editButtonItem;

which produces a regular edit/done button at

4条回答
  •  有刺的猬
    2021-02-01 18:18

    For those who don't want to override UITableView (e.g. if you're using UITableViewController), here's a simple and clean solution that I use. It basically involves creating your own edit button item and using the tableView's editing flag to track edit vs done. For icing on the cake, it shows a "+" button (instead of "Edit") when the table is empty for adding new items.

    - (void) updateEditButtonVisibility
    {
        // tableItems represents the data structure that s
        if ([tableItems count] > 0)
        {
            UIBarButtonSystemItem editButtonType = self.tableView.editing ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit;
            UIBarButtonItem *editButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:editButtonType
                                                                                            target:self
                                                                                            action:@selector(editButtonTouched)];
    
            self.navigationItem.rightBarButtonItem = editButtonItem;
            [editButtonItem release];
        }
        else
        {
            UIBarButtonItem *addButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                                                                                           target:self
                                                                                           action:@selector(addButtonTouched)];
            self.navigationItem.rightBarButtonItem = addButtonItem;
            [addButtonItem release];
        }
    }
    
    - (void) editButtonTouched
    {
        // edit/done button has been touched
    
        [self.tableView setEditing:!self.tableView.editing animated:YES];
        [self updateEditButtonVisibility];
    }
    
    - (void) addButtonTouched
    {
        // logic to allow user to add new items goes here
    }
    
    - (void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
    
        [self updateEditButtonVisibility];
    }
    

提交回复
热议问题