我正在将包含美国州数据的字典元素数组加载到 UITableView 中,当用户向下滚动到屏幕外项目时,我遇到了重复的行 - 第 1 行在第 8 行重复,第 2 行在第 9 行重复,等等。
我已经查看了以下 SO 问题并实施了他们的一些建议(没有成功):
2994472 - 我的 UITableView 有重复的行
7056578 - UITableView 滚动时重复单元格
UITableViewCell 是一个自定义结构,由 UILabel 创建。这是 cellForRowAtIndexPath 中的代码。
00 const int ABBREVIATION = 1, STATE = 2 // Declared outside cellForRowAtIndexPath
01 static NSString *CellIdentifier = @"Cell";
02
03 UILabel *abbreviation, *state;
04
05 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
06 if (cell == nil) {
07 cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
08 reuseIdentifier:CellIdentifier];
09
10 abbreviation = [[UILabel alloc] initWithFrame:CGRectMake(7.0, 1.0, 34.0, 30.0 )];
11 abbreviation.tag = ABBREVIATION;
12 abbreviation.font = [UIFont fontWithName:@"Helvetica-Bold" size:20.0];
13 abbreviation.textAlignment = UITextAlignmentLeft;
14 abbreviation.textColor = [UIColor blackColor];
15
16 state = [[UILabel alloc] initWithFrame:CGRectMake(42.0, 1.0, 158.0, 30.0)];
17 state.tag = STATE;
18 state.font = [UIFont fontWithName:@"Helvetica-Bold" size:20.0];
19 state.textAlignment = UITextAlignmentLeft;
20 state.textColor = [UIColor blackColor];
21
22 [cell.contentView addSubview:abbreviation];
23 [cell.contentView addSubview:state];
24
25 [cell setAccessoryType:UITableViewCellAccessoryDetailDisclosureButton];
26 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
27 }
28
29 abbreviation.text = [[self.primaries objectAtIndex:indexPath.row] objectForKey:@"abbreviation"];
30 state.text = [[self.stateInfo objectAtIndex:indexPath.row] objectForKey:@"name"];
31
32 return cell;
按照 2994472 中的建议,我将第 27 行和第 28 行修改为使用三元运算符。
29 abbreviation.text = [[self.primaries objectAtIndex:indexPath.row] objectForKey:@"abbreviation"] ?
[[self.primaries objectAtIndex:indexPath.row] objectForKey:@"abbreviation"] :
@"";
30 state.text = [[self.stateInfo objectAtIndex:indexPath.row] objectForKey:@"name"] ?
[[self.stateInfo objectAtIndex:indexPath.row] objectForKey:@"name"] :
@"";
那没有用,重复仍然从第 8 行开始发生。
似乎解决问题的方法是在设置标签文本以深入查看实际子视图时引用 UILabel 标记。
29 ((UILabel *)[cell viewWithTag:ABBREVIATION]).text = [[self.primaries objectAtIndex:indexPath.row] objectForKey:@"abbreviation"];
30 ((UILabel *)[cell viewWithTag:STATE]).text = [[self.primaries objectAtIndex:indexPath.row] objectForKey:@"name"];
当以这种方式引用单元格子视图时, UITableView 行重复消失。