2016-01-31 102 views
-3

这里要说明的问题是:编程的图像设定为图像视图使多个图像在一个表视图细胞

enter image description here

正如你所看到的,有显示在彼此顶部的多张图片在表格视图单元格中。我想只显示最上面的图片。下面是导致此行为上面的tableview细胞的相关代码:

func cellTwo(indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("cellTwo", forIndexPath: indexPath) as! CathyTaskLogTwoTableViewCell 

    let pictureImageView = UIImageView() 
    pictureImageView.contentMode = .ScaleAspectFit 
    pictureImageView.frame.size.width = 100 
    pictureImageView.frame.size.height = 100 

    cell.pictureMessageTextView.addSubview(pictureImageView) 
    pictureImageView.image = pictures[indexPath.row] 

    return cell 

} 

因此,为了去除多张照片显示我下面的代码添加到上面的函数:

for subview in cell.pictureMessageTextView.subviews { 
     print(cell.pictureMessageTextView.textContainer) 
     if subview != pictureImageView { 
      if subview != cell.pictureMessageTextView.textContainer { 
       subview.removeFromSuperview() 
      } 

     } 
    } 

然而,这将导致多个图片的问题消失,但会使文本dissapear像这样:

enter image description here

我想在保留文字的同时只显示一张图片。任何人都可以更好地解决这个问题?

回答

1

问题是单元格被重复使用。你需要考虑到你已经给这个单元格的图像视图的可能性。

当您添加图像视图时,给它一个独特的tag。在此之前,请使用viewWithTag来确定您是否已添加图像视图。如果有,请不要添加它!

现在你知道只有一个图像视图,并且使用viewWithTag可以获得对它的引用。为其分配适合此行的图像。完成。

0

我建议你声明的图像查看你的电池的性能,而当它的零,从而增加你的重用细胞不会有重复的图像视图只ALLOC它:

let cell = tableView.dequeueReusableCellWithIdentifier("cellTwo", forIndexPath: indexPath) as! CathyTaskLogTwoTableViewCell 

let pictureImageView = cell.pictureImageView 
if (!pictureImageView) { 
    pictureImageView = UIImageView() 
    pictureImageView.contentMode = .ScaleAspectFit 
    pictureImageView.frame.size.width = 100 
    pictureImageView.frame.size.height = 100 

    cell.pictureImageView = pictureImageView 
    cell.pictureMessageTextView.addSubview(pictureImageView) 
} 
pictureImageView.image = pictures[indexPath.row] 

return cell