在单元格中添加uiimageview



尝试在单元格内加载图像。我可以在单元格中加载图像,但当上下滚动表格时,图像也会随机出现在其他不同的单元格中。。。

这是一些代码:

- (UITableViewCell *)tableView:(UITableView *)tableView_ cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView_ dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];

}
if (indexPath.section == ONE_SECTION) {
switch(indexPath.row) {
case 0:{
//some code
}
break;
case 2:{
//some code
}
break;
case 3:{

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(256,0,43,43)];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:imageView];
imageView.layer.cornerRadius = 10.0;
//imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.layer.masksToBounds = YES;
imageView.image = [UIImage imageNamed:@"imageName.png"];}
break;
default:
break;
}
}
if (indexPath.section == TWO_SECTION) {
//some code
}
if (indexPath.section == THREE_SECTION) {
//some code
}

return cell;
}

谢谢

尝试使用以下代码。如果要重用单元格,则不必向所有单元格重复添加imageView。您可以在单元分配部分创建它,只需在它的外部设置imageView.image属性,如下所示。

- (UITableViewCell *)tableView:(UITableView *)tableView_ cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView_ dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(256,0,43,43)];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[cell.contentView addSubview:imageView];
imageView.layer.cornerRadius = 10.0;
//imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.layer.masksToBounds = YES;
imageView.tag = 567; //unique tag
}
UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:567];
imageView.image = nil;
if (indexPath.section == ONE_SECTION) {
switch(indexPath.row) {
case 0:{
//some code
}
break;
case 2:{
//some code
}
break;
case 3:{
UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:567];
imageView.image = [UIImage imageNamed:@"imageName.png"];
}
break;
default:
break;
}
}
if (indexPath.section == TWO_SECTION) {
//some code
}
if (indexPath.section == THREE_SECTION) {
//some code
}
return cell;
}

更好的方法是创建自定义UITableViewCell类,并在该单元格的init方法中添加UIImageView。然后在cellForRowAtIndexPath方法中将属性设置为cell.imageView.image = ...

由于您使用的是缓存单元格,因此您得到的单元格可能是您在上一次代码调用中添加了图像视图的单元格。如果您为图像视图指定了一个唯一的tag,那么在不需要它的情况下,您可以检查它的存在,如果找到它,可以将其删除。

最新更新