iOS tableView删除,添加,排序方法实现

来源:互联网 发布:js rsa加密 php解密 编辑:程序博客网 时间:2024/05/22 07:03

这里的删除方式有两种,一种是滑动删除,一种是点击"-"号删除按钮再删除。

将下面的注释去掉后实现的是点击按钮删除,未去掉的情况下是滑动删除。

注意下面的list数组是可变数组哦!

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

   static NSString *cellId =@"cell";

   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];

   if(cell == nil){

        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellId];

    }

    cell.textLabel.text = [listobjectAtIndex:indexPath.row];

    

   return cell;

    

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

   return [listcount];

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

   return 1;

}

//没有实现该方法的时候,默认是滑动删除的

//决定单元格编辑状态

//-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{

//    //return action == 0 ? UITableViewCellEditingStyleDelete :

//   // UITableViewCellEditingStyleInsert;

   

//}


//删除指定行时指定的确认文本

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{

    return@"确定删除";

}

//DataSourse协议,决定某行是否可以编辑

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{

   if(indexPath.row ==0){

       return NO;

    }else{

       return  YES;

    }

    return YES;

    

}

//DataSourse协议,移动完成时激发该方法

-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{

   NSInteger originRow = sourceIndexPath.row;

   NSInteger destRow = destinationIndexPath.row;

   id target = [listobjectAtIndex:originRow];

    [listremoveObjectAtIndex:originRow];

    [listinsertObject:target atIndex:destRow];

    

}

//编辑(包括删除或插入)完成时激发该方法

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    if (editingStyle ==UITableViewCellEditingStyleDelete) {

       NSInteger originRow = indexPath.row;

        [listremoveObjectAtIndex:indexPath.row];

        [tableView deleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

    }elseif(editingStyle ==UITableViewCellEditingStyleInsert){

        //在当前行的下一行插入数据

        [listinsertObject:[listobjectAtIndex:indexPath.row]atIndex:(indexPath.row +1)];

        [tableView insertRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    }

}



0 0