您的位置:首页 > 产品设计 > UI/UE

UITableView删除多行

2015-11-09 14:34 302 查看
主要是-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath  这个方法,返回1是删除,返回2是插入,3是复选框。

直接来代码吧:

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
UITableView *_tableView;
NSMutableArray *_dataArray;
NSMutableArray *_arrayForDelete;
NSMutableArray *_indexPathArray;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

[self prepareData];
[self uiConfig];

}

-(void)prepareData
{
_indexPathArray = [[NSMutableArray alloc]init];
_arrayForDelete = [[NSMutableArray alloc]init];
_dataArray = [[NSMutableArray alloc]init];
for (int i = 0; i<20; i++) {
[_dataArray addObject:[NSString stringWithFormat:@"%d行",i]];
}

}

-(void)uiConfig
{
_tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];

self.navigationItem.rightBarButtonItem = self.editButtonItem;

}

//点击右上角edit按钮的时候调用
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
[_tableView setEditing:editing animated:animated];
if (editing == NO) {
[_dataArray removeObjectsInArray:_arrayForDelete];
// [_tableView reloadData];//刷新
[_arrayForDelete removeAllObjects];
[_tableView deleteRowsAtIndexPaths:_indexPathArray withRowAnimation:UITableViewRowAnimationFade];
[_indexPathArray removeAllObjects];
}
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 3;
//或者 return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid = @"cellid";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
}
cell.textLabel.text = _dataArray[indexPath.row];
return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}

//选择的时候调用,将需要删除的cell的数据源和索引存起来
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[_arrayForDelete addObject:_dataArray[indexPath.row]];
[_indexPathArray addObject:indexPath];
}

//当反选的时候调用,就是取消选择的时候调用
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[_arrayForDelete removeObject:_dataArray[indexPath.row]];
[_indexPathArray removeObject:indexPath];
}

@end


效果:



点击Edit:



选择:



点击Done:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息