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

效果图如下:

   


作者:老Zhan
出处:http://www.cnblogs.com/mybkn/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 
原文地址:https://www.cnblogs.com/mybkn/p/2543091.html