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

iOS UITableView实现滑动删除、增加、多选

2015-01-19 16:47 701 查看
实现滑动删除,动态增加,以及cell的多选只需要添加cell 的三个代理函数。
1.这个函数是判断每一个cell是否可编辑
-(BOOL)tableView:(UITableView
*)tableView canEditRowAtIndexPath:(NSIndexPath
*)indexPath
2.这个函数是返回编辑的类型
-(UITableViewCellEditingStyle)tableView:(UITableView
*)tableView editingStyleForRowAtIndexPath:(NSIndexPath
*)indexPath
3.这个函数是编辑后的操作。但是多选例外。需要借助selected函数
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath

废话不多说,直接上代码。。清晰明了
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor
= [UIColor redColor];
 
self.tableView
= [[UITableView alloc] initWithFrame:CGRectMake(0,
0,
320, self.view.frame.size.height-64)
style:UITableViewStylePlain];
_tableView.delegate
= self;
_tableView.dataSource
= self;
[self.view
addSubview:_tableView];
 
 
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑"
style:UIBarButtonItemStyleBordered target:self action:@selector(rightItemEvents:)];
self.navigationItem.rightBarButtonItem
= rightItem;
}

-(void)rightItemEvents:(UIBarButtonItem *)item
{
_tableView.editing
= !_tableView.editing;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"选中:%d段%d行",indexPath.section,indexPath.row);
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
//在这里做你想做的
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSLog(@"删除");
}else
if (editingStyle == UITableViewCellEditingStyleInsert){
NSLog(@"增加");
}else{
NSLog(@"段:%d",indexPath.section);
}
 
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
//是否允许编辑
return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath
*)indexPath
{
//设置编辑的类型
 
return UITableViewCellEditingStyleInsert
| UITableViewCellEditingStyleDelete;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 5;
 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios TableView