2016-03-08 75 views
0

我正在使用UICollectionView和自定義UICollectionViewCell。爲了實例我的手機在cellForItemAtIndexPathdidSelectItemAtIndexPath,我用這條線:使用didHighlightItemAtIndexPath實例化自定義UICollectionViewCell

let music_Cell:MusicCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("music_Cell", forIndexPath: indexPath) as! MusicCollectionViewCell 

通過這種方式,我能夠在我的自定義音樂細胞打電話,然後我可以基於該狀態操縱它歌曲(如果它已經播放,等等)。

例如,我可以處理這樣的細胞:

music_Cell.song_Title_Label.text = song_Title! 

在功能我只返回music_Cell結束。一切工作正常.... UNTIL

在我看來,我沒有實例我自定義的小區,其功能didHighlightItemAtIndexPathunHighlight功能,因爲這些功能不允許你返回一個自定義的功能UICollectioViewCell 。我希望能夠在人物突出顯示時自定義UI更改。到目前爲止,我已經能夠做的唯一事情就是實例化一個普通細胞,而不是我的自定義的:

let cell: UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)! 
cell.contentView.backgroundColor = opus_Page_Primary_Color 

但我希望能夠控制其他UI元素,而不僅僅是背景色。

我該怎麼做?我到處看過?

+0

嘗試獲取與indexPath集合視圖的原始細胞。在UITableView類似self.tableview.cellForRowAtIndexPath(...)。肯定有一個收集視圖的等價物。 –

+0

對不起。沒有看到你最後的代碼。我在移動。在該行後面添加「as MyCustomCellClass」。 –

+0

@KevinLieser你是對的。我所要做的就是用我的自定義類(MusicCollectionViewCell)的名稱替換UICollectionViewCell並添加「as!MusicCollectionViewCell」。 –

回答

0

您在自定義UICollectionViewCell子類中處理選擇和突出顯示的外觀。

class MyCell: UICollectionViewCell { 
    override var selected: Bool { 
     didSet { 
      print("selected") // Do your custom selection state here. 
     } 
    } 

    override var highlighted: Bool { 
     didSet { 
      print("highlighted") // Do you custom highlighting here. 
     } 
    } 
} 

您還可以利用selectedBackgroundView屬性。將其設置爲自定義視圖將在當所選單元格動畫該視圖的單元格背景鑑於以上:

public var selectedBackgroundView: UIView? 

注意:你應該離隊可重複使用的細胞唯一的一次是在cellForItemAtIndexPath(這就是爲什麼與其他代表方法不返回UICollectionViewCell)。

0

解決方案:

我所要做的就是用我的自定義CollectionViewCell類的名稱替換UICollectionViewCell

let cell: MusicCollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath) as! MusicCollectionViewCell! 

現在我可以訪問所有我的自定義類的元素,像這樣:

cell.song_Title_Label.text = "Song Name" 
相關問題