1. 程式人生 > >ios之UITableView批量選中cell並實現刪除cell的簡單方法

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