0

I have this code implemented in my tableView:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return NO;
    }
    return YES;
}

It does what I want, but I want to go one step better and make "section 0" disappear altogether when the edit button is pressed (this effect can be seen if you go into the "keyboard" menu on iOS and select edit in the top right corner, the top two sections disappear in an animation). I have attempted to temporarily remove the first section, but my app crashes when [tableView reloadData]; is called:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tvController.editing == YES) {
        return 1;
    }else if (tvController.editing == NO) {
        return 2;
    }
    return 0;
}

Also, I do not think I will end up with an animation if I get that code working, I think my approach is wrong. Thanks for your help guys!

4

1 回答 1

1

Your problem

One of your sections is longer than the preceding one.

Since you hide section 0 by reporting 1 less section in numberOfSectionsInTableView:, in editing mode every delegate method must adjust the section number. One of them is not doing so.

// every delegate method with a section or indexPath must adjust it when editing

- (NSInteger) tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tvController.editing) section++;
    return [[customers objectAtIndex:section] count];
}

- (UITableViewCell*) tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath
{
    int section = indexPath.section;
    if (tvController.editing) section++;

    id customer = [[customers objectAtIndex:section] indexPath.row];

    // etc
}

My approach

UITableView reloadSections:withRowAnimation: reloads specified sections with an animation. Call it from your setEding:animated: delegate method.

- (void) setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];

    UITableViewRowAnimation animation = animated ? UITableViewRowAnimationFade : UITableViewRowAnimationNone;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:animation];

    [self.tableView reloadSectionIndexTitles];

    self.navigationItem.hidesBackButton = editing;
}

Your delegate also needs indicate that the hidden section has no rows or title.

- (NSInteger) tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.editing && section == 0) {
        return 0;
    }

    return [[customers objectAtIndex:section] count];
}

- (NSString*) tableView:(UITableView*) tableView titleForHeaderInSection:(NSInteger) section
{
    if (self.editing && section == 0) {
        return nil;
    }

    [[customers objectAtIndex:section] title];
}
于 2012-07-04T15:26:20.030 回答