2017-04-06 46 views
1

我想設置一個新的顏色的圖像,而UICollectionView的單元格被選中或取消選擇。每當我不設置它的圖像色調的顏色,但我不想有它的默認色彩blue。所以我在做什麼是:色調的圖像不想改變

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell功能,我inicialazing我的圖片,代碼:

let borderWidth = itemBorder.frame.width 
      let borderHeight = itemBorder.frame.height 

      myImage = UIImageView(frame: CGRect(x: 0, y: 0, width: borderWidth - 1/4 * borderWidth, height: borderHeight - 1/5 * borderHeight)) 
      myImage.image = UIImage(named: myCollection[indexPath.row])?.withRenderingMode(.alwaysTemplate) 
      myImage.tintColor = UIColor.groupTableViewBackground 
      myImage.center = CGPoint(x: tmpCell.bounds.width/2, y: tmpCell.bounds.height/2) 
      myImage.contentMode = .scaleAspectFit 
      tmpCell.contentView.addSubview(myImage) 

等在didselected和取消功能:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     let currentCell: UICollectionViewCell? 
     switch collectionView { 
     case myCollectionView: 
      print("clicked") 
      currentCell = myCollectionView.cellForItem(at: indexPath)! 
       currentCell?.tintColor = UIColor.white 

     case colorsCollectionView: 
      break 
     default: 
      break 
     } 
    } 

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { 
     let currentCell: UICollectionViewCell? 
     switch collectionView { 
     case vehiclesCollectionView: 
      print("deselected") 
      currentCell = myCollectionView.cellForItem(at: indexPath)! 
      currentCell?.tintColor = UIColor.groupTableViewBackground 
     case colorsCollectionView: 
      break 
     default: 
      break 
     } 
    } 

有人能告訴我最新怎麼了? 在此先感謝!

解決方案

解決方案 每當我想更新我在小區指向在圖像上的顏色的色調,從而basiclly只需要添加到選擇或取消選擇的方法是:

currentCell = myCollectionView.cellForItem(at: indexPath)! 
      let image = currentCell?.contentView.subviews[1] as! UIImageView 
      image.tintColor = UIColor.white 

回答

1

我看到你設置currentCell?.tintColor,但我想你可能要設置currentCell?.vehicleImageView.image.tintColor

而且我看到你代碼有點混亂,因爲你有vehicleImage(它應該可能被命名爲vehicleImageView)和myImage這是一個UIImage它被添加爲contentView的子視圖嗎?我認爲只能添加UIView的子類作爲子視圖。

我建議你在你的自定義UICollectionViewCell創建一個名爲myImageView的插座中可以設置image.tintColor和改變cell.myImageView.tintColordidSelectdidDeselect

如果不從故事板添加它們,你仍可以創建UICollectionViewCell的子類具有名爲vehicleImageView的屬性。您可以根據您的要求在cellForRow中設置此框架和圖像。現在您將擁有一個物業,您可以在didSelectdidDeselect中參考cell.vehicleImageView.image.tintColor

如果您不想創建具有屬性的子類,則基本上必須遍歷所有子視圖,然後找到圖像視圖並在那裏設置圖像tintColor。設置tintColorUICollectionViewCell不會解決問題。你將不得不將它設置爲imageView.image

希望有幫助!

+0

你是對的,我沒有改變所有的名字。要做到這一點! – yerpy

+0

感謝您的接受和upvoting! –

+0

我很抱歉,但它不起作用:C – yerpy