最近在实现UITableView的编辑cell功能时,发现有些淡忘这一块东西了.所以,姑且写一篇博客复习一下这块的知识吧.本文主要拿删除cell来讲,插入其实一模一样,就不单独说了.
删除cell,就我目前遇到的来说,主要由两种,一种是侧滑删除cell,还有一种就是点击删除cell.侧滑删除,想必大家一定很熟悉,今天我主要说说点击删除.如下图:
这样的点击删除cell,我第一次看,觉得很简单,就是发送一条请求,删除这条数据,然后刷新一下UITableView就好了.但是当我这样写了,却发现错了.
然后我才发现自己想错了.我们在实现侧滑删除的时候,一般都是在下面这个代理方法中,先删除数据源,然后在删除cell.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView beginUpdates];
if (editingStyle ==UITableViewCellEditingStyleDelete) {
NSLog(@"删除");
//第一,删除数据源,
[_arrremoveObject:_arr[indexPath.row]];
//第二,删除表格cell
// [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
[tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation: UITableViewRowAnimationRight];
}else{
//第一,插入数据源
[_arrinsertObject:@"张三"atIndex:indexPath.row];
//第二,插入cell.
[tableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationLeft];
NSLog(@"添加");
}
[tableView endUpdates];
}
我现在要实现的功能其实跟侧滑删除一样,也不所以我也要做上面的操作,先删除数据源,然后再删除cell.然后我还要做的是发送请求,后台删除,数据库中的这一条数据,跟我前端上面保持一致.
我想明白了,然后剩下的就是编码了.下面是部分源码
#pragma mark ------- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
MDWGirlInfoViewController *viewController = (MDWGirlInfoViewController *)self.controller;
MDWFocusRequest *request=[[MDWFocusRequestalloc] init];
MDWRequestManager *manager=[MDWRequestManagermanager];
if (buttonIndex ==1) {
NSString * path = [@"/status/"stringByAppendingString:_statusId];
//第一步,先发送网络请求删除数据
[manager sendWithoutResponseRequest:pathmethod:@"DELETE"paras:nilbody:request onSuccess:^(AFHTTPRequestOperation *operartion,id responseObject) {
//第二步,删除数据源
NSMutableArray *mutableArray=[NSMutableArrayarrayWithArray:_modelData];
[mutableArray removeObjectAtIndex:[indexPathrow]];
_modelData=[NSArrayarrayWithArray:mutableArray];
//第三步,删除cell
[self.tableViewdeleteRowsAtIndexPaths:[NSArrayarrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
} onFailure:^(AFHTTPRequestOperation *operation,NSError *error) {
}];
}
}
在UITableView中插入或者删除指定的行(或者节)使用的是如下几个API:
- insertRowsAtIndexPath: withRowAnimation: 在指定位置插入行
- deleteRowsAtIndexPath: withRowAnimation: 删除指定行
- insertSections: withRowAnimation: 在指定位置插入节
- deleteSections: withRowAnimation: 删除指定节
好了,按照这样写完,就搞定这个功能了,原谅我就不举例插入cell了.原理跟删除cell一样.......