2017-10-19 349 views
0
class SceneCell: UICollectionViewCell { 

    override var isSelected: Bool { 
     didSet { 
      setSelected(bool: isSelected) 
     } 
    } 

    override var isHighlighted: Bool { 
     didSet { 
      setHighlighted(bool: isHighlighted) 
     } 
    } 

    @IBOutlet weak var thumbnailImageView: UIImageView! 

    override func draw(_ rect: CGRect) { 
     super.draw(rect) 

     self.backgroundColor = .clear 
     self.thumbnailImageView.layer.borderColor = UIColor.green.cgColor 
     self.thumbnailImageView.layer.masksToBounds = true 
     self.thumbnailImageView.clipsToBounds = true 
     self.thumbnailImageView.layer.cornerRadius = 8 
    } 

    func update(with scene: Scene) { 

    } 

    private func setHighlighted(bool: Bool) { 
     if bool { 
      self.alpha = 0.5 
     } else { 
      self.alpha = 1.0 
     } 
    } 

    private func setSelected(bool: Bool) { 
     if bool { 
      self.thumbnailImageView.layer.borderWidth = 2.5 
     } else { 
      self.thumbnailImageView.layer.borderWidth = 0 
     } 
    } 
} 

在我的代碼中,當被選中時,我將圖像視圖的圖層邊框寬度更改爲2.5設置爲true。使用屬性觀察器更改集合視圖單元格很不好嗎?

當我選擇一個單元格並滾動集合視圖時,我認爲當重用該選定單元格時單元格保持選中狀態,但重用單元格更改爲未選中狀態。其次,當我回到選定的單元格並重新使用未選中的單元格時,我認爲它處於未選定狀態。但是單元格是自動設置的。

劑量收集視圖自動管理這些?

回答

0

該問題的代碼工作完美。這是一個替代解決方案,用於記錄單元格的選擇並應用於選定/取消選擇狀態的設置。

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource { 
    //...... 

    var selectedIndexPaths = [IndexPath]() 

    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     selectedIndexPaths.append(indexPath) 
    } 

    public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { 
     if let index = selectedIndexPaths.index(of: indexPath) { 
      selectedIndexPaths.remove(at: index) 
     } 
    } 

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
     //... 
     cell.setSelected(selectedIndexPaths.contains(indexPath)) //Remember to make the cell's setSelected() public. 
     //... 
    } 

    //...... 
} 
+0

但我的代碼完美地工作。 – Sohn

+0

與重複使用問題完美結合使用?我想它在沒有滾動的情況下工作完美,是嗎? –

+0

它沒有重用問題。我的問題是爲什麼這個代碼運行良好。 – Sohn

相關問題