2013-06-25 25 views
1

我有一個UITableView,在每個部分中有不同的行數。 我做了代碼,試圖獲得一個正確的結果:錯誤的單元格UITableView的每個值

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    static NSString *CellIdentifier= @"channel"; 
    ChannelsCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if(!cell) { 
     cell =[[ChannelsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    } 

    NSInteger rowsCountSection = [[arrayofChannelsCount objectAtIndex:indexPath.section] intValue];// this variable has the number of rows of every section 

    NSUInteger pos = indexPath.section*count+ indexPath.row; 

    cell.channelName.text=[arrayofChannelName objectAtIndex:pos]; 

    return cell; 
} 

我敢肯定這是一個數學問題。

謝謝你的幫助。

編輯:

NSMutableArray *arrayofChannelsOffsets=[[NSMutableArray alloc]initWithCapacity:[arrayofChannelsCount count]]; 
    NSNumber* zero = [NSNumber numberWithInteger:0]; 
    [arrayofChannelsOffsets addObject:zero]; 

    for (int j=1; j<[arrayofChannelsCount count]; j++) { 
      NSUInteger sum=(int)[arrayofChannelsOffsets objectAtIndex:j-1]+(int)[arrayofChannelsCount objectAtIndex:j-1]; 
      NSNumber* num = [NSNumber numberWithInteger:sum]; 
      [arrayofChannelsOffsets addObject:num]; 

      NSLog(@"%lu count offset:",(unsigned long)[arrayofChannelsOffsets count]); 
      } 

     for (int i= 0 ; i < indexPath.section ; i++) { 
      pos =[[arrayofChannelsOffsets objectAtIndex:i] intValue] + indexPath.row; 
       } 
     cell.channelName.text=[arrayofChannelName objectAtIndex:pos]; 

我有奇怪的錯誤:

'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 267575552 beyond bounds [0 .. 101]' 

從哪裏是數量龐大267575552真的來了。

回答

1

在這樣的情況下,你需要在此之前一個總量可達行的所有部分的數量,而不是使用indexPath.section*count

NSUInteger pos = indexPath.row; 
for (int = 0 ; i < indexPath.section ; i++) { 
    pos += [[arrayofChannelsCount objectAtIndex:i] intValue]; 
} 
cell.channelName.text=[arrayofChannelName objectAtIndex:pos]; 

注意,代碼是有些多餘:它重複相同的計算一遍又一遍的爲每個細胞。您可以添加一個新的NSArray *arrayofChannelsOffsets,它與arrayofChannelsCount具有相同數量的項目,但不包含個別計數,每個項目應包含小於當前值的部分中的計數總和。有了這樣的一個數組你可以通過寫

NSUInteger pos = [[arrayofChannelsOffsets objectAtIndex:i] intValue] + indexPath.row; 
+0

感謝您的回答。問題解決了90%。我不知道爲什麼它以arrayofChannelName的第一個(1)元素開頭,而不是0元素(我會稍後嘗試優化代碼,如您注意到的那樣)。 – androniennn

+1

@androniennn我想我犯了一個錯誤 - 用循環中的<<替換循環中的<='應該可以解決問題。 – dasblinkenlight

+0

大尊敬的人!你總是最好的:)。現在我會更好地優化你告訴我的代碼。非常感謝你,你讓我的一天:)。 – androniennn

0

嘗試:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 

參考TableViewSuite

+0

的問題,避免循環不段的行數,但是行的價值觀 – androniennn

相關問題