开发者

iOS: editingStyleForRowAtIndexPath when adding a new cell

I'm adding a row to a UITableView section when the user switches the table to editing mode with this code:

- (void) setEditing:(BOOL) editing animated:(BOOL) animated {
    [super setEditing:editing animated:animated];
    if (editing) {
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject: [NSIndexPath indexPathForRow:0 inSection:SECTION_SUPPLIERS]]   withRowAnimation:UITableViewRowAnimationFade];
    } 
}

The object being to create a "Add new supplier ..." row. This works, however when the table wants to get the editing style so it can add a plus or minus icon, I have a problem.

- (UITableViewCellEditingStyle) tableView:(UITableView *) tableView editingStyleForRowAtIndexPath:(NSIndexPath *) indexPath {
    return ([self.tableView isEditing] && indexPath.row == 0) ? U开发者_如何学GoITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}

The sequence seems to go like this:

  1. The table switches to editing. There is only one supplier row at this time so it queries for a editing style with row == 0.
  2. The insert of the new row is done which then triggers another query for an editing style again with a row == 0.

So if I use this sequence and use the row number and tableView isEditing to decide on the editing style icon I end up with both the Add new and current supplier rows with plus icons on them.

What is the best way to insert a row and assign the appropriate editing style - plus for the add new row, and minus for any other row?


Have you tried putting your "Add new..." row at the bottom instead of at the top? Instead of checking for [indexPath row] == 0 you instead check for [indexPath row] == [items count], and your tableView:numberOfRowsInSection: implementation looks like this:

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
    int numberOfRows = [items count];

    if ([self isEditing]) {
        numberOfRows++;
    }

    return numberOfRows;
}

This is how the example in iPhone Programming: The Big Nerd Ranch Guide works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜