1

我有一个 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 确实来自哪里。

4

2 回答 2

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;
于 2013-06-25T16:02:34.327 回答
0

尝试 :

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

请参阅TableViewSuite

于 2013-06-25T14:27:47.250 回答