您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS TableView 多選刪除完整實作:思路解析與純代碼範例

編輯:iOS 開發綜合

做 iOS 不算久,很多控件都是邊工作邊學。最近因為專案需求又研究了一次多選刪除,網上的 demo 雖然多,但大多是 Storyboard 拉出來的,而且不少細節沒考慮到。以下是自己重新理解後寫的純代碼版本,供大家參考。

先講思路

多選刪除其實可以拆成四個步驟:

1. 準備原始資料

NSMutableArray *dataArray;   // 原始資料

2. 準備一個暫存「已勾選項目」的陣列

NSMutableArray *removeList;  // 勾選時要刪除的資料

3. 按下刪除按鈕時,一次執行三件事

[_dataArray removeObjectsInArray:self.removeList];  // 刪除已勾選的資料
[tableView reloadData];                             // 重新載入
[self.removeList removeAllObjects];                 // 清空已勾選的暫存列表

4. 實作三個 delegate 方法:切換編輯樣式、選取一項、取消選取一項。

概念就是這麼簡單。以下完整代碼,但建議不要直接複製貼上,先自己理解一遍動手寫過,才是你的。

完整代碼

#import "ViewController.h"

@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
{
    UITableView *tableView;
}
@property (nonatomic, strong) NSMutableArray *dataArray;   // 原始資料
@property (nonatomic, strong) NSMutableArray *removeList;  // 已勾選待刪除
@property (nonatomic, strong) UIBarButtonItem *rightBtn;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initAllData];
}

#pragma mark - 初始化

- (void)initAllData {
    // 1. 建立並加入 tableView
    tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 320,
                                     self.view.frame.size.height - 64)];
    [self.view addSubview:tableView];
    tableView.delegate = self;
    tableView.dataSource = self;

    // 2. 初始化資料
    _dataArray = [[NSMutableArray alloc] initWithObjects:@"王菲", @"周迅", @"李冰冰",
                    @"白冰", @"紫薇", @"馬蘇", @"劉詩詩", @"趙薇", @"angelbaby",
                    @"熊黛林", nil];
    self.removeList = [[NSMutableArray alloc] init];

    // 3. 導航欄設定
    self.view.backgroundColor = [UIColor whiteColor];
    UINavigationBar *navbar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 64)];
    [navbar setBackgroundColor:[UIColor clearColor]];

    NSShadow *shadow = [[NSShadow alloc] init];
    [shadow setShadowOffset:CGSizeMake(0, 0)];
    [navbar setTitleTextAttributes:@{
        NSForegroundColorAttributeName : [UIColor orangeColor],
        NSShadowAttributeName : shadow
    }];

    // 4. 建立導航項
    UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:@"多選刪除"];

    // 5. 狀態欄樣式
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;

    // 6. 建立右側按鈕
    _rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"刪除"
                                                style:UIBarButtonItemStyleDone
                                               target:self
                                               action:@selector(toggleEdit:)];
    self.navigationItem.rightBarButtonItem = _rightBtn;
    [navItem setRightBarButtonItem:_rightBtn];

    // 7. 加入導航欄
    [navbar pushNavigationItem:navItem animated:NO];
    [self.view addSubview:navbar];
}

#pragma mark - 多選刪除操作(重點)

- (void)toggleEdit:(id)sender {
    // 切換編輯狀態,這一行就會讓每列左側出現勾選圓圈
    [tableView setEditing:!tableView.editing animated:YES];

    if (tableView.editing) {
        [self.navigationItem.rightBarButtonItem setTitle:@"確定"];
    } else {
        [self.navigationItem.rightBarButtonItem setTitle:@"刪除"];

        if (self.removeList.count > 0) {
            [_dataArray removeObjectsInArray:self.removeList];  // 刪除已勾選資料
            [tableView reloadData];                             // 重新載入
            [self.removeList removeAllObjects];                 // 清空暫存列表
        }
    }
}

#pragma mark - UITableViewDataSource

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *DeleteMeCellIdentifier = @"DeleteMeCellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DeleteMeCellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                     reuseIdentifier:DeleteMeCellIdentifier];
    }

    NSInteger row = [indexPath row];
    cell.textLabel.text = [_dataArray objectAtIndex:row];
    return cell;
}

#pragma mark - UITableViewDelegate

// 編輯樣式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

// 勾選一項
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = [indexPath row];
    id addObject = [_dataArray objectAtIndex:row];
    [self.removeList addObject:addObject];
}

// 取消勾選一項
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = [indexPath row];
    id deleteObject = [_dataArray objectAtIndex:row];
    [self.removeList removeObject:deleteObject];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

兩個容易忽略的細節

第一,removeObjectsInArray: 比對的是元素內容而非 index,因此若資料中有重複值,一次會刪掉所有相同的項目。資料可能重複時,建議改為收集 NSIndexPath 後逐一刪除,或改用「以 index 反查 identifier」的方式比對。

第二,didSelectRowAtIndexPath 在非編輯模式下也會被觸發。若希望只有在編輯模式才累積勾選清單,記得加上 tableView.editing 的判斷,否則使用者只是點一下 cell 就會被誤加入待刪列表。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved