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

UITableView 進入編輯模式:刪除、插入與拖曳排序的完整實作

編輯:iOS 開發綜合

UITableView 的編輯能力內建在 controller 與 delegate 的一整套方法裡,只要把該實作的回呼補齊,刪除、插入、跨列排序都能直接跑起來。以下用一個分區列表為例,把整個流程走一遍。

準備資料與表格

viewDidLoad 裡建立三個分區的資料,並用系統自帶的編輯按鈕取代自己刻的 UIBarButtonItem:

- (void)viewDidLoad {
    [super viewDidLoad];

    // 亞洲
    _arr1 = [NSMutableArray arrayWithObjects:@"中國", @"新加坡", @"蒙古", nil];
    // 美洲
    NSMutableArray *arr2 = [NSMutableArray arrayWithObjects:@"美國", @"加拿大", @"巴西", nil];
    // 歐洲
    NSMutableArray *arr3 = [NSMutableArray arrayWithObjects:@"英國", @"法國", @"德國", nil];

    // 把三個分區放進大陣列
    _dataArray = [[NSMutableArray alloc] initWithObjects:_arr1, arr2, arr3, nil];

    // 直接用 controller 自帶的 editButtonItem,不必自己建立物件
    self.navigationItem.rightBarButtonItem = self.editButtonItem;

    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorColor = [UIColor greenColor];
}

讓編輯狀態同步給 tableView

controller 的 setEditing:animated: 是切換入口,重寫它並把狀態轉給表格,同時改寫按鈕文字:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [_tableView setEditing:editing animated:animated];
    self.editButtonItem.title = editing ? @"完成" : @"編輯";
}

哪些列可編輯、編輯樣式為何

// 預設就是 YES
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

// 預設為刪除樣式,也可改成插入
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
    // return UITableViewCellEditingStyleInsert;
}

完成編輯:先改資料,再改畫面

這裡最容易踩的坑就是順序顛倒。務必先動数据源,再呼叫 deleteRows / deleteSections,否則會直接 crash,畫面上也會出現列數對不上的怪現象。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSMutableArray *onegroup = _dataArray[indexPath.section];
        if (onegroup.count == 1) {
            // 該分區只剩一列,就把整個分區刪掉
            [_dataArray removeObject:onegroup];
            NSIndexSet *set = [NSIndexSet indexSetWithIndex:indexPath.section];
            [_tableView deleteSections:set withRowAnimation:UITableViewRowAnimationLeft];
        } else {
            [onegroup removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }

    if (editingStyle == UITableViewCellEditingStyleInsert) {
        NSMutableArray *onegroup = _dataArray[indexPath.section];
        [onegroup addObject:@"北京"];
        [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    }
}

移動排序

能不能拖、拖到哪去、放下的時候怎麼改資料,分別由三個方法負責:

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

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
       toIndexPath:(NSIndexPath *)destinationIndexPath {
    NSMutableArray *onegroup = _dataArray[sourceIndexPath.section];
    // 先 retain 起來,避免移除當下物件被釋放
    NSString *name = [onegroup[sourceIndexPath.row] retain];
    [onegroup removeObject:name];
    [onegroup insertObject:name atIndex:destinationIndexPath.row];
    [name release];
}

// 限制只能在同一個 section 內移動
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
    if (sourceIndexPath.section == proposedDestinationIndexPath.section) {
        return proposedDestinationIndexPath;
    }
    return sourceIndexPath;
}

資料來源方法

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

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

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"分區:%ld 行數:%ld", indexPath.section, indexPath.row);
}

整份程式背後其實只有一個原則:UITableView 是資料的檢視,所有編輯動作都要「先改 model、再改 view」。把這條規則守住,刪除、插入、排序三件事就不會出亂子。

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