2013-08-23 29 views
1

我有一個表視圖控制器,所有美國州按字母順序部分列出。點擊狀態可通過Web服務調用返回關於狀態的詳細信息。這是我在分段或分組表格視圖中的第一次嘗試,並且在過去'A'的行上遇到索引路徑問題。例如,如果我點擊'C'組中的第一項'California',那麼indexpath.row屬性是0而不是4,這是因爲CA是按字母順序排列的第五個狀態,應該有4分段表視圖索引路徑問題

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; 

    //get the letter in the current section 
    NSString *letter = [stateIndex objectAtIndex:[indexPath section]]; 
    //get all the states beginning with the letter 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", letter]; 
    NSArray *states = [stateKeys filteredArrayUsingPredicate:predicate]; 
    if([states count] > 0){ 
     //get relevant state from states object 
     NSString *cellValue = [states objectAtIndex:indexPath.row]; 
     [[cell textLabel] setText:cellValue];   
    }  
    return cell; 
} 

,並在我的塞克indexpath.row,設置在該方法的最後一行一個斷點表明itemRowIndex是不正確的(當然除了,對於「A」組) :

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 
    if([segue.identifier isEqualToString:@"sgShowStateRivers"]){ 
     RiversByStateTableViewController *riversVC = [segue destinationViewController]; 
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 
     NSInteger itemRowIndex = indexPath.row; 
     NSString *key = [stateKeys objectAtIndex:itemRowIndex]; 
     [riversVC setStateIdentifier:[statesDict objectForKey:key]]; 
    } 
} 

怎麼會有一個分組的表格視圖,其中的項目仍然是數字因爲它們在原始數組中?謝謝! V

+0

你的數組的結構是什麼?通常,當你做一個分區表視圖時,你使用一個數組數組,每個內部數組提供一個部分的行(在你的情況下,所有的狀態都以相同的字母開始)。爲什麼你想讓CA的indexPath.row爲4而不是0? – rdelmar

回答

1

您在UITableView的背景下對NSIndexPath s的理解不正確。 row屬性重置爲表中每個單獨部分的0。

你有兩種簡單的方式前進:

  • 你可以做的是做一個2維數組(一個「數組的數組」),其中第一級是每個部分和第二級別中的每一行。這使您可以直接使用索引路徑的rowsection來進行數組查找。

  • prepareForSegue:sender:中,您可以遍歷各個部分並統計行數,直到您到達indexPathForSelectedRow.section,然後將indexPathForSelectedRow.row添加到該數量。這會給你一個索引,你可以使用它從你的1維數組中獲取狀態信息。