2012-11-12 17 views
-1

我試圖在不依賴indexPaths的情況下檢查tableView中的一行。這與我之前詢問過的問題類似,但這看起來應該比它容易。檢查表中的一行查看

我有一個靜態值的數組是我的tableView的數據源,稱之爲fullArray。當選擇一行時,它的值被放置在另一個數組中 - 讓我們稱它爲partialArray。之前當我用indexPaths做這件事時,我會用這個遍歷partialArray:

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

工程就像一個魅力。但是,現在我試圖用partial array中的值來做到這一點,並且我遇到了麻煩。

以下是我認爲它應該在我的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; 
    } 
} 

似乎並不像它應該是這麼辛苦,但我不能換我的頭周圍。

回答

0

我不知道你爲什麼要改變存儲索引路徑,但這是你的電話。此外,您可能希望使用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; 
}]; 
+0

數組名只是爲了這個緣故發佈以使其可讀。至於從indexPaths移動,這是因爲我的搜索顯示控制器在這張桌子上。也許我的整個方法是錯誤的。當我在該表上搜索時,它會過濾到結果,並且當您選擇該結果(indexpath 0,0),然後清除搜索時,它將檢查整個表中的indexPath 0,0 - 這是不正確的。猜測我應該解決我過濾的表格複選標記。思考? – Selch