现在的位置: 首页 > 综合 > 正文

IOS-UITableView入门(3)

2014年11月09日 ⁄ 综合 ⁄ 共 1891字 ⁄ 字号 评论关闭

UITableView本身自带了(增、删)编辑功能:

1.只要调用UITableView的编辑代码 就会进入编辑状态:

[self.tableView setEditing:!self.tableView.editing animated:YES];

2.进入编辑状态的UITableView会调用代理的

- (UITableViewCellEditingStyle) tableView:(UITableView
*)tableView editingStyleForRowAtIndexPath:以便判断是增加还是删除的方法。

UITableViewCellEditingStyle为一个枚举值,如UITableViewCellEditingStyleDelete,UITableViewCellEditingStyleInsert

整体的代码如下:

#pragma mark 点击编辑删除
- (IBAction)trashClick:(id)sender {
    self.tableView.tag=EDIT_MOVE;
    [self.tableView setEditing:!self.tableView.editing animated:YES];
}

#pragma mark -TableViewDataSource
#pragma mark 当出现编辑状态时 如果是删除状态时 点击删除保存时调用的方法
#pragma mark 当为增加状态事 点击增加按钮保存时调用的方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag==20)
    {
        [self.arr removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
    else
    {
        [self.arr insertObject:@"new row..." atIndex:indexPath.row+1];
        NSIndexPath *indexNew=[NSIndexPath indexPathForRow:indexPath.row+1 inSection:0];
        [tableView insertRowsAtIndexPaths:@[indexNew] withRowAnimation:UITableViewRowAnimationRight];
    }
    
}

#pragma mark 点击编辑时出现的删除或者增加的按钮
- (UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag==20)
    {
        return UITableViewCellEditingStyleDelete;
    }
    else
    {
        return UITableViewCellEditingStyleInsert;
    }
}

#pragma mark 移动item时,以便编辑模式后还能保存编辑的顺序
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSString *currStr=self.arr[sourceIndexPath.row];
    [self.arr removeObjectAtIndex:sourceIndexPath.row];
    [self.arr insertObject:currStr atIndex:destinationIndexPath.row];
    [tableView reloadData];
}

#pragma mark 点击编辑增加
- (IBAction)addClick:(id)sender {
    self.tableView.tag=EDIT_ADD;
    [self.tableView setEditing:!self.tableView.editing animated:YES];
}

删除、移动的界面增加item的界面

抱歉!评论已关闭.