簡體   English   中英

檢查 tableView 中的一行

[英]Check a row in tableView

我試圖在不依賴 indexPaths 的情況下檢查 tableView 中的一行。 這類似於我之前問過的一個問題,但這似乎應該比現在更容易。

我有一個靜態值數組,它是我的 tableView 的數據源,稱之為 fullArray。 當一行被選中時,它的值被放置在另一個數組中——我們稱之為partialArray。 在我使用 indexPaths 執行此操作之前,我會使用以下命令遍歷 partialArray:

for(NSIndexPath * elem in [[SharedAppData sharedStore] selectedItemRows]) { 
    if ([indexPath compare:elem] == NSOrderedSame) { 
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}

奇跡般有效。 但是,現在我正在嘗試使用部分數組中的值來執行此操作,但遇到了麻煩。

這是我認為它應該如何在我的 sudo 代碼中的 cellForRowAtIndexPath 方法中工作:

對於 fullArray 中的每個字符串,如果它在 partialArray 中,則獲取它的 indexPath 並檢查它。

我開始拼湊的代碼:

for(NSString *string in fullArray) {
    if (partialArray containsObject:string) {
//Need help here. Get the index of the string from full array
    fullArray indexOfObject:string];
//And check it.

        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
}

看起來不應該那么難,但我無法理解它。

我不知道您為什么要放棄存儲索引路徑,但這就是您的要求。 此外,您可能希望使用NSMutableSet來存儲您選中的項目而不是數組。 例如,更好的變量名稱是checkedItems而不是partialArray

無論如何,如果您只需要遍歷fullArray的元素並獲取每個元素的索引,則可以使用兩種方法之一。 一種方法是使用普通的舊 C 循環,例如for語句:

for (int i = 0, l = fullArray.count; i < l; ++i) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
        continue;
    NSString *item = [fullArray objectAtIndex:i];
    cell.accessoryType = [partialArray containsObject:item]
        ? UITableViewCellAccessoryCheckmark
        : UITableViewCellAccessoryNone;
    }
}

另一種方法是使用enumerateObjectsWithBlock:方法:

[fullArray enumerateObjectsUsingBlock:^(id item, NSUInteger index, BOOL *stop) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
        return;
    cell.accessoryType = [partialArray containsObject:item]
        ? UITableViewCellAccessoryCheckmark
        : UITableViewCellAccessoryNone;
}];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM