ios之UITableView批量选中cell并实现删除cell的简单方法

主要实现思路:重写tableViewCell 在cell前面添加一个imageView两种图片来标识是否是选中状态  并且cell 的.h 文件定义两个方法设置cell选中状态图片   然后定义一个标识数组和数据源相对应,当初始化数据的的时候把所有cell标识为未选中,并且标识用字典来存放它的两个状态 这就方便与数据对应和状态对应,当删除的时候需要对两个数据都进行删除,然后在对TableView进行数据更新;

</pre><pre name="code" class="objc">
<pre name="code" class="objc">#import "ViewController.h"
#import "LTableViewCell.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *table;
    NSMutableArray *dataSource;
    NSMutableArray *contacts;
    UIButton *button;
}
- (void)deleteSelect;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    dataSource = [NSMutableArray array];
    contacts = [NSMutableArray array];
	// Do any additional setup after loading the view, typically from a nib.
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 320, 500) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    [self.view addSubview:table];
    for (int i = 0; i <50; i++) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:@"NO" forKey:@"checked"];
        [contacts addObject:dic];
        [dataSource addObject:[NSString stringWithFormat:@"     %d",i]];
    }
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"全选" forState:UIControlStateNormal];
    button.frame = CGRectMake(10, 10, 100, 50);
    [button addTarget:self action:@selector(allSelect:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    UIButton * deleButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [deleButton setTitle:@"批量删除" forState:UIControlStateNormal];
    deleButton.frame = CGRectMake(110, 10, 100, 50);
    [deleButton addTarget:self action:@selector(deleteSelect) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:deleButton];
}
// 初始化让所有cell 未选中
- (void)allSelect:(UIButton*)sender{
    // 获取所有可用的indexPaths
    NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[table indexPathsForVisibleRows]];
    // 遍历indexPaths
    for (int i = 0; i < [anArrayOfIndexPath count]; i++) {
        NSIndexPath *indexPath= [anArrayOfIndexPath objectAtIndex:i];
        // 取出每个indexPaths对应的cell
        LTableViewCell *cell = (LTableViewCell*)[table cellForRowAtIndexPath:indexPath];
        NSUInteger row = [indexPath row];
        NSLog(@"%lu",(unsigned long)row);
        // 出去每个indexPaths所对应的标识
        NSMutableDictionary *dic = [contacts objectAtIndex:row];
        // 如果点击的是全选
        if ([[[(UIButton*)sender titleLabel] text] isEqualToString:@"全选"]) {
            [dic setObject:@"YES" forKey:@"checked"]; // 把标识改为yes
            [cell setChecked:YES]; // 更改cell的图片
        }else {
            [dic setObject:@"NO" forKey:@"checked"];
            [cell setChecked:NO];
        }
    }
    // 对button的标题进行更改 并把所有的标识更改 (上面更改的只是显示部分的而不是所有的)
    if ([[[(UIButton*)sender titleLabel] text] isEqualToString:@"全选"]){
        for (NSDictionary *dic in contacts) {
            [dic setValue:@"YES" forKey:@"checked"];
        }
         [(UIButton*)sender setTitle:@"取消" forState:UIControlStateNormal];
    }else{
        for (NSDictionary *dic in contacts) {
            [dic setValue:@"NO" forKey:@"checked"];
        }
        [(UIButton*)sender setTitle:@"全选" forState:UIControlStateNormal];
    }
}

#pragma mark - TableView dataSource and delegate

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * identifier = @"Cell";
    LTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[LTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }else
    {
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    NSUInteger row = [indexPath row];
    NSMutableDictionary *dic = [contacts objectAtIndex:row];
    if ([[dic objectForKey:@"checked"] isEqualToString:@"NO"]) {
        [dic setObject:@"NO" forKey:@"checked"];
        [cell setChecked:NO];
        
    }else {
        [dic setObject:@"YES" forKey:@"checked"];
        [cell setChecked:YES];
    }
    cell.textLabel.text = dataSource[row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld",indexPath.row);
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 获取点击的cell
    LTableViewCell *cell = (LTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    
    NSUInteger row = [indexPath row];
    // 获取点击cell的标识
    NSMutableDictionary *dic = [contacts objectAtIndex:row];
    // 如何是选中改成未选中,如果是为选中改成选中
    if ([[dic objectForKey:@"checked"] isEqualToString:@"NO"]) {
        [dic setObject:@"YES" forKey:@"checked"];
        [cell setChecked:YES];
    }else {
        [dic setObject:@"NO" forKey:@"checked"];
        [cell setChecked:NO];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark - DeleteSelect cell

- (void)deleteSelect
{
    
    NSMutableIndexSet *indexs = [NSMutableIndexSet indexSet];
    // 遍历选中的数据源的index并添加到set里面
    for (int i = 0; i < contacts.count; i ++) {
        if ([contacts[i][@"checked"] isEqualToString:@"YES"]) {
            [indexs addIndex:i];
        }
    }
    //  删除选中数据源 并更新tableView
    [dataSource removeObjectsAtIndexes:indexs];
    [contacts removeObjectsAtIndexes:indexs];
    [table reloadData];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 重写cell 定义好需要用的属性  
#import <UIKit/UIKit.h>

@interface LTableViewCell : UITableViewCell{
    BOOL			m_checked;
    UIImageView*	m_checkImageView;
}
- (void)setChecked:(BOOL)checked;
@end


#import "LTableViewCell.h"

@implementation LTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        [self creat];
    }
    return self;
}
// 创建cell
- (void)creat{
    if (m_checkImageView == nil)
    {
        m_checkImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Unselected.png"]];
        m_checkImageView.frame = CGRectMake(10, 10, 29, 29);
        [self addSubview:m_checkImageView];
    }
}


// 设置选中或未选中图片
- (void)setChecked:(BOOL)checked{
    if (checked)
	{
		m_checkImageView.image = [UIImage imageNamed:@"Selected.png"];
		self.backgroundView.backgroundColor = [UIColor colorWithRed:223.0/255.0 green:230.0/255.0 blue:250.0/255.0 alpha:1.0];
	}
	else
	{
		m_checkImageView.image = [UIImage imageNamed:@"Unselected.png"];
		self.backgroundView.backgroundColor = [UIColor whiteColor];
	}
	m_checked = checked;
    
    
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值