2016-11-14 57 views
0

我有條件僅顯示幾行圖片。但是當我滾動時,圖像也顯示爲其他隨機行。下面是我的代碼:UITableViewCell圖像在滾動條件下無法正常顯示

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) 
     //var data = objectArray[indexPath.section].sectionObjects[indexPath.row] as? NSDictionary 
     if let data = objectArray[indexPath.section].sectionObjects[indexPath.row] as? NSDictionary{ 
      if let name = data.objectForKey("NAME") as? String{ 
       cell.textLabel?.text = name 
      } 
      if completedTrainings.contains((data.objectForKey("MENU_ID") as? Int)!) { 
       cell.imageView?.frame = CGRect(x: (cell.bounds.width-110), y: 0, width: 100, height: 100) 
       cell.imageView?.image = UIImage(named: "CORRECT") 
      } 
     } 
     return cell 
    } 

圖片應該僅在菜單ID在完成培訓存在,但上滾動出現在一些隨機的細胞以及出現。圖像也在左邊,但它應該在右邊。我怎樣才能把它移到正確的位置?

+0

如果要將圖像放在右側,請創建自定義表格視圖單元格。 –

+0

添加此行, cell.imageView?.image = UIImage() –

+2

單元格被重用,您必須通過添加'else'子句將所有UI元素設置爲某個狀態。 – vadian

回答

1

因爲imageUIImageView可選U可以將圖像設置爲nil如果妳不想要在你的代碼,以顯示例如圖像,作爲vadian建議

 cell.imageView?.image = nil //reset the cell image first 
    cell.textLabel?.text = "" 
    if let data = objectArray[indexPath.section].sectionObjects[indexPath.row] as? NSDictionary{ 
     if let name = data.objectForKey("NAME") as? String{ 
      cell.textLabel?.text = name 
      cell.imageView?.image = nil //add this line 
     } 
     if completedTrainings.contains((data.objectForKey("MENU_ID") as? Int)!) { 
      cell.imageView?.frame = CGRect(x: (cell.bounds.width-110), y: 0, width: 100, height: 100) 
      cell.imageView?.image = UIImage(named: "CORRECT") 
     } 
1

嘿,你需要創建你自己的自定義UITableViewCell子類,無論是在故事板或筆尖文件中,並註冊該視圖控制器中的那個筆尖文件。這將使您可以選擇使用任何佈局來設計您想要的任何單元格。您在隨機單元格上看到此圖像的原因是因爲您的單元格正在被重用,並且如果您沒有找到圖像(如果completedTrainings.contains),則不會將imageView設置爲隱藏或將其圖像設置爲空圖像(也許這是一個特殊的圖像)。

1

雖然處理可重複使用的電池。嘗試使用if和else兩者。只有這樣才能解決問題。