iphone: 可编辑的tableView Move&Delete

设置一个Button,点击可以删除,移动排序tableView,效果图如下:左边为移动,右边为删除

                                     

先说移动:

button要设置IBAction

- (IBAction)toggleMove {
    [self.tableView setEditing:!self.tableView.editing animated:YES];
    
    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Move"];
}

self.tableView.editing属性是个bool型,表示tableView的编辑状态

这里设置button为两种文字,对应不同状态。

然后实现三个委托方法即可:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView
canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
      toIndexPath:(NSIndexPath *)toIndexPath {
    NSUInteger fromRow = [fromIndexPath row];
    NSUInteger toRow = [toIndexPath row];
    
    id object = [list objectAtIndex:fromRow];
    [list removeObjectAtIndex:fromRow];
    [list insertObject:object atIndex:toRow];
}

删除的则更简单了。

其button的action与上面一样,

只要实现一个委托方法:

- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSUInteger row = [indexPath row];
    [self.list removeObjectAtIndex:row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                     withRowAnimation:UITableViewRowAnimationAutomatic];
}

 

也可以将二者结合起来,实现上面的4哥委托方法就行。只是要注意在editingStyleForRowAtIndexPath 方法种,返回UITableViewCellEditingStyleDelete

效果图如下:

posted on 2012-06-09 14:44  老Zhan  阅读(1675)  评论(0编辑  收藏  举报