Iphone uitableviewcell的子视图存在问题
我向uitableviewcells添加了一个子视图,它工作正常,但当我向上或向下滚动时,子视图会添加多次。我不知道我错在哪里 这是我的密码:Iphone uitableviewcell的子视图存在问题,iphone,Iphone,我向uitableviewcells添加了一个子视图,它工作正常,但当我向上或向下滚动时,子视图会添加多次。我不知道我错在哪里 这是我的密码: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"MainPageCellView"; MainPageTableCe
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"MainPageCellView";
MainPageTableCellView *cell = (MainPageTableCellView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"MainPageTableCellView" owner:self options:nil];
cell = mainPageTableCell;
}
[cell setNameText:[namesArray objectAtIndex:indexPath.row]];
[cell setPositionText:[positionArray objectAtIndex:indexPath.row]];
[cell setCompanyNameText:[companyNameArray objectAtIndex:indexPath.row]];
[cell setDistanceText:[distArray objectAtIndex:indexPath.row]];
[cell setImageViewImage:[imagesArray objectAtIndex:indexPath.row]];
UIImage *halo = [UIImage imageNamed:@"h1.png"];
UIImageView *haloV = [[UIImageView alloc] initWithImage:halo];
if(indexPath.row == 0)
[cell addSubview: haloV];
else if(indexPath.row ==2)
[cell addSubview: haloV];
else if(indexPath.row ==3)
[cell addSubview: haloV];
return cell;
}
您正在将子视图添加到单元中,无论它们是否刚刚创建或正在重用。当您上下滚动时,它们会被重用,因此子视图会被重复添加 在if(cell==nil)块中移动对addSubview的调用,这应该可以解决问题
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"MainPageTableCellView" owner:self options:nil];
cell = mainPageTableCell;
UIImage *halo = [UIImage imageNamed:@"h1.png"];
UIImageView *haloV = [[UIImageView alloc] initWithImage:halo];
if(indexPath.row == 0)
[cell addSubview: haloV];
else if(indexPath.row ==2)
[cell addSubview: haloV];
else if(indexPath.row ==3)
[cell addSubview: haloV];
}