这里的删除方式有两种,一种是滑动删除,一种是点击"-"号删除按钮再删除。
将下面的注释去掉后实现的是点击按钮删除,未去掉的情况下是滑动删除。
注意下面的list数组是可变数组哦!
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellId = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if(cell == nil){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
cell.textLabel.text = [list objectAtIndex:indexPath.row];
return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [list count];
}
-(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 = [list objectAtIndex:originRow];
[list removeObjectAtIndex:originRow];
[list insertObject:target atIndex:destRow];
}
//编辑(包括删除或插入)完成时激发该方法
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSInteger originRow = indexPath.row;
[list removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}else if(editingStyle == UITableViewCellEditingStyleInsert){
//在当前行的下一行插入数据
[list insertObject:[list objectAtIndex:indexPath.row] atIndex:(indexPath.row + 1)];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}