iOS开发之-Table View-Inserting and Deleting Rows and Sections

Inserting and Deleting Rows and Sections




Inserting and Deleting Rows in Editing Mode




1. If a UIViewController object is managing the table view, it automatically receives a setEditing:animated: message when the Edit button is tapped.

2. When the table view receives setEditing:animated:, it sends the same message to the UITableViewCell object for each visible row.

3.

After resending setEditing:animated: to the cells corresponding to the visible rows, the sequence of messages is as follows:

  1. The table view invokes the tableView:canEditRowAtIndexPath: method if its data source implements it. This method allows the application to exclude rows in the table view from being edited even when their cell’seditingStyle property indicates otherwise. 
  2. The table view invokes the tableView:editingStyleForRowAtIndexPath: method if its delegate implements it. This method allows the application to specify a row’s editing style and thus the editing control that the row displays.At this point, the table view is fully in editing mode.
  3. If he or she taps a deletion control, a Delete button is displayed on the row. The user then taps that button to confirm the deletion.
  4. The table view sends the tableView:commitEditingStyle:forRowAtIndexPath: message to the data source. Although this protocol method is marked as optional, the data source must implement it if it wants to insert or delete a row. It must do two things:


4.When the user swipes a row to delete it, the table view first checks to see if its data source has implemented thetableView:commitEditingStyle:forRowAtIndexPath: method; if that is so, it sends setEditing:animated: to itself and enters editing mode. In this “swipe to delete” mode, the table view does not display the editing and reordering controls. Because this is a user-driven event, it also brackets the messages to the delegate inside of two other messages: tableView:willBeginEditingRowAtIndexPath: and tableView:didEndEditingRowAtIndexPath:. By implementing these methods, the delegate can update the appearance of the table view appropriately.


An Example of Deleting a Table-View Row


self.navigationItem.rightBarButtonItem = self.editButtonItem;

1. This button is preconfigured to send setEditing:animated: to the view controller when tapped; it toggles the button title (between Edit and Done) and the Boolean editing parameter on alternating taps. 


Listing 7-1  View controller responding to setEditing:animated:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [tableView setEditing:editing animated:YES];
    if (editing) {
        addButton.enabled = NO;
    } else {
        addButton.enabled = YES;
    }
}

Listing 7-2  Customizing the editing style of rows
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    SimpleEditableListAppDelegate *controller = (SimpleEditableListAppDelegate *)[[UIApplication sharedApplication] delegate];
    if (indexPath.row == [controller countOfList]-1) {
        return UITableViewCellEditingStyleInsert;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
}


2. The user taps the deletion control in a row and the view controller receives a tableView:commitEditingStyle:forRowAtIndexPath: message from the table view. 


Listing 7-3  Updating the data-model array and deleting the row
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    // If row is deleted, remove it from the list.
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        SimpleEditableListAppDelegate *controller = (SimpleEditableListAppDelegate *)[[UIApplication sharedApplication] delegate];
        [controller removeObjectFromListAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

An Example of Adding a Table-View Row

Listing 7-4  Adding an Add button to the navigation bar
    addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItem:)];
    self.navigationItem.rightBarButtonItem = addButton;

Listing 7-5  Responding to a tap on the Add button
- (void)addItem:sender {
    if (itemInputController == nil) {
        itemInputController = [[ItemInputController alloc] init];
    }
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:itemInputController];
    [[self navigationController] presentModalViewController:navigationController animated:YES];
    [navigationController release];
}

- (void)save:sender {
 
    UITextField *textField = [(EditableTableViewTextField *)[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]] textField];
 
    SimpleEditableListAppDelegate *controller = (SimpleEditableListAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString *newItem = textField.text;
    if (newItem != nil) {
            [controller insertObject:newItem inListAtIndex:[controller countOfList]];
    }
    [self dismissModalViewControllerAnimated:YES];
}


Batch Insertion, Deletion, and Reloading of Rows and Sections

Listing 7-7  Batch insertion and deletion methods
- (void)beginUpdates;
- (void)endUpdates;
 
- (void)insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
- (void)reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation;
 
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation: (UITableViewRowAnimation)animation;
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation: (UITableViewRowAnimation)animation;
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;

1. The reloadSections:withRowAnimation: and reloadRowsAtIndexPaths:withRowAnimation: methods, allow you to request the table view to reload the data for specific sections and rows instead of loading the entire visible table view by calling reloadData.


An Example of Batched Insertion and Deletion Operations


1. To insert and delete a group of rows and sections in a table view, first prepare the array (or arrays) that are the source of data for the sections and rows. After rows and sections are deleted and inserted, the resulting rows and sections are populated from this data store.

Next, call the beginUpdates method, followed by invocations of insertRowsAtIndexPaths:withRowAnimation:, deleteRowsAtIndexPaths:withRowAnimation:, insertSections:withRowAnimation:, or deleteSections:withRowAnimation:. Conclude the animation block by calling endUpdates.


Listing 7-8  Inserting and deleting a block of rows in a table view
- (IBAction)insertAndDeleteRows:(id)sender {
    // original rows: Arizona, California, Delaware, New Jersey, Washington
 
    [states removeObjectAtIndex:4]; // Washington
    [states removeObjectAtIndex:2]; // Delaware
    [states insertObject:@"Alaska" atIndex:0];
    [states insertObject:@"Georgia" atIndex:3];
    [states insertObject:@"Virginia" atIndex:5];
 
    NSArray *deleteIndexPaths = [NSArray arrayWithObjects:
                                [NSIndexPath indexPathForRow:2 inSection:0],
                                [NSIndexPath indexPathForRow:4 inSection:0],
                                nil];
    NSArray *insertIndexPaths = [NSArray arrayWithObjects:
                                [NSIndexPath indexPathForRow:0 inSection:0],
                                [NSIndexPath indexPathForRow:3 inSection:0],
                                [NSIndexPath indexPathForRow:5 inSection:0],
                                nil];
    UITableView *tv = (UITableView *)self.view;
 
    [tv beginUpdates];
    [tv insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationRight];
    [tv deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
    [tv endUpdates];
 
    // ending rows: Alaska, Arizona, California, Georgia, New Jersey, Virginia
}

Ordering of Operations and Index Paths


You might have noticed something in the code shown in Listing 7-8 that seems peculiar. The code calls the deleteRowsAtIndexPaths:withRowAnimation: method after it calls insertRowsAtIndexPaths:withRowAnimation:. However, this is not the order in which UITableView completes the operations. It defers any insertions of rows or sections until after it has handled the deletions of rows or sections.

Inserting or removing an item in a mutable array, on the other hand, may affect the array index used for the successive insertion or removal operation

An example is useful here. Say you have a table view with three sections, each with three rows. Then you implement the following animation block:

  1. Begin updates.
  2. Delete row at index 1 of section at index 0.
  3. Delete section at index 1.
  4. Insert row at index 1 of section at index 1.
  5. End updates


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值