每个部分的 UITableView 单元格值错误 [英] Wrong cells values of UITableView per section
问题描述
我有一个 UITableView,它在每个部分都有不同的行数.我编写了该代码以尝试获得正确的结果:
I have a UITableView that has a different rows count in every section. I made that code to try achieving a correct result:
- (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;
}
我很确定这是一个数学问题.
I'm pretty sure that's a mathematic problem.
感谢您的帮助.
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 是从哪里来的.
From where that huge number 267575552 did come.
推荐答案
在这种情况下,您需要将所有节中的行数加总,而不是使用 indexPath.section*count代码>:
In cases like this, you need to total up the number of rows in all sections prior to this one rather than using 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
相同,但不是包含单个计数,每个项目应包含部分少于当前的部分.使用这样的数组,您可以通过编写
Note that the code is somewhat redundant: it repeats the same calculations over and over for each cell. You can add a new NSArray *arrayofChannelsOffsets
which has the same number of items as arrayofChannelsCount
, but rather than containing the individual count, each item should contain the sum of counts in the sections less than the current one. With an array like that you'd be able to avoid the loop by writing
NSUInteger pos = [[arrayofChannelsOffsets objectAtIndex:i] intValue] + indexPath.row;
这篇关于每个部分的 UITableView 单元格值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!