2016-01-31 100 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