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

iOS UITableView 全選與多選功能實作

編輯:iOS 開發綜合

在 UITableView 中實作多選與全選,常見做法是為每一列維護一個選取狀態,並在點擊時更新資料來源與 Cell 樣式。

1. 多選處理

在 didSelectRowAtIndexPath 中切換該列的選取狀態:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    Custom *cell = (Custom *)[tableView cellForRowAtIndexPath:indexPath];
    NSUInteger row = [indexPath row];
    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];
    }
}

2. Cell 中的選取狀態

在自訂 Cell 中可加入 BOOL 屬性與設定方法:

@property (nonatomic, assign) BOOL checked;

- (void)setChecked:(BOOL)checked {
    _checked = checked;
    // 更新勾選樣式
}

3. 全選處理

全選時,可遍歷可見或全部資料,將 checked 設為 YES:

NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[contactList indexPathsForVisibleRows]];

for (int i = 0; i != [contacts count]; i++) {
    NSIndexPath *indexPath = [anArrayOfIndexPath objectAtIndex:i];
    Custom *cell = (Custom *)[contactList cellForRowAtIndexPath:indexPath];
    NSUInteger row = [indexPath row];
    NSMutableDictionary *dic = [contacts objectAtIndex:row];

    if ([[[(UIButton *)sender titleLabel] text] isEqualToString:@"全選"]) {
        [dic setObject:@"YES" forKey:@"checked"];
        [cell setChecked:YES];
    } else {
        [dic setObject:@"NO" forKey:@"checked"];
        [cell setChecked:NO];
    }
}

4. 注意事項

若需要跨頁或跨區段保持選取狀態,建議將選取狀態存在資料模型中,而不是只依賴 Cell 的視覺狀態。Cell 會被重用,若狀態只存在 Cell 上,捲動後可能會顯示錯誤。

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