IOS:自定义UITableViewCell - 滚动后的奇怪行为

时间:2013-05-15 12:25:35

标签: ios layout uitableview

我有一个带有自定义表格单元格的TableView。我在每个单元格的底部以编程方式添加边框以保持屏幕设计布局。当应用程序第一次加载时,一切都很好。但滚动(并向上滚动到顶部)后,屏幕上会显示多条边框线。

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

...

if([object.cellMessageArray[1] isEqualToString:@"wrapper"] || [object.cellMessageArray[1] isEqualToString:@"keynote"] || [object.cellMessageArray[1] isEqualToString:@"break"]) {
UIImageView *lineSeparator = [[UIImageView alloc] initWithFrame:CGRectMake(0, cell.bounds.size.height, 1024, 5)];
lineSeparator.image = [UIImage imageNamed:[NSString stringWithFormat:@"blind.png" ]];
lineSeparator.backgroundColor = [UIColor whiteColor];
[cell.contentView addSubview:lineSeparator];
}
else if([object.cellMessageArray[1] isEqualToString:@"standard"]) {
UIImageView *lineSeparator = [[UIImageView alloc] initWithFrame:CGRectMake(60, cell.bounds.size.height+4, 1024, 1)];
lineSeparator.image = [UIImage imageNamed:[NSString stringWithFormat:@"blind.png" ]];
lineSeparator.backgroundColor = [UIColor pxColorWithHexValue:@"eeeeee"];
[cell.contentView addSubview:lineSeparator];
}
}

有人有想法吗?

1 个答案:

答案 0 :(得分:2)

滚动tableview时,将重复使用单元格(dequeueReusableCellWithIdentifier)以优化性能。在上面的代码中,每次调用lineSeparator方法时,都会向单元格添加cellForRowAtIndexPath图像视图。如果单元格使用了5次,则会添加5个图像视图。

解决此问题的一种方法是在重用之前从单元格中删除lineSeparator图像视图。这通常在单元格的prepareForReuse方法中完成。

cellForRowAtIndexPath中,为lineSeparator图片视图添加标记(例如lineSeparator.tag = 100;

在您的单元格类中,实现prepareForReuse方法。 E.g:

-(void)prepareForReuse{
    UIView *lineSeparatorView = [self.contentView viewWithTag:100];
    [lineSeparatorView removeFromSuperview];
}
相关问题