在cellForRowAtIndexPath
我正在向UIImageView
添加cell.contentView
。问题是当单元格从屏幕滚动并重新打开时,它会在已经存在的图像上再次添加相同的图像。这种情况持续发生,直到我得到一个非常叠加的模糊图像。
您是否必须继续删除添加到cell.contentView
的所有图片视图?如果是这样,你使用什么委托方法?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CellIdentifier";
MyTableCell *cell = (MyTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.jpg"]];
imageView.center = CGPointMake(310, 48);
[cell.contentView addSubview:imageView];
[imageView release];
return cell;
}
答案 0 :(得分:3)
如果您不想继续将imageView放在单元格中,则必须在if(cell==nil)
块内进行所有自定义,否则每次单元回收时都会添加一个。使用单元格回收时,您总是希望保留该块中所有单元格的一致性,以便它们只添加一次。
例如:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CellIdentifier";
MyTableCell *cell = (MyTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
//Add custom objects to the cell in here!
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.jpg"]];
imageView.center = CGPointMake(310, 48);
[cell.contentView addSubview:imageView];
[imageView release];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
答案 1 :(得分:1)
如果每个单元格需要不同的图像,您可以尝试这样的方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CellIdentifier";
static const int ImageViewTag = 1234; //any integer constant
MyTableCell *cell = (MyTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIImageView *imageView;
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
//Add custom objects to the cell in here!
imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, imgWidth, imgHeight)];
imageView.center = CGPointMake(310, 48);
imageView.tag = ImageViewTag;
[cell.contentView addSubview:imageView];
[imageView release];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else
{
imageView = [cell viewWithTag:ImageViewTag];
}
imageView.image = yourUIImageForThisCell;
return cell;
}