只能選擇一個項目,我實現UICollectionViewController的子類,是水平滾動,我希望它能夠在一次只能選擇一個項目。在UICollectionViewController
當我改變當前屏幕上所選擇的項目,它工作正常。但是,例如,如果我在集合的最開始處選擇一個項目,然後向右滾動並選擇另一個,則第一個項目仍將被選中。
這裏的當前版本我的CollectionView的:
class GenresCollectionVC: UICollectionViewController {
var selectedIndexPath: IndexPath?
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return MockData.instance.genres.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: reuseIdentifier, for: indexPath) as! GenreCollectionViewCell
cell.genreNameLabel.text = MockData.instance.genres[indexPath.row]
if selectedIndexPath == indexPath {
redraw(selectedCell: cell)
} else {
redraw(deselectedCell: cell)
}
return cell
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? GenreCollectionViewCell else {
return
}
redraw(selectedCell: cell)
selectedIndexPath = indexPath
}
override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? GenreCollectionViewCell else {
return
}
redraw(deselectedCell: cell)
selectedIndexPath = nil
}
private func redraw(selectedCell cell: GenreCollectionViewCell
) {
cell.layer.borderWidth = 1.0
cell.layer.cornerRadius = cell.bounds.height/2
cell.layer.borderColor = UIColor.violetNeeoColor.cgColor
cell.genreNameLabel.textColor = UIColor.violetNeeoColor
}
private func redraw(deselectedCell cell: GenreCollectionViewCell) {
cell.layer.borderWidth = 0.0
cell.layer.cornerRadius = 0.0
cell.genreNameLabel.textColor = UIColor.white
}
}
我在做什麼錯?
酷,它幫助我!但是可以解釋爲什麼我們應該調用'super.isSelected = newValue'?刪除這一行代碼現在不會改變我的程序中的任何內容 – Legonaftik
不改變任何東西意味着如果您刪除此行,程序無法工作? – PGDev
不,一切正常,當我使用你的代碼。即使我刪除了'super.isSelected = newValue'這行,一切仍然有效。所以問題是:「爲什麼我應該寫這條線,它會發生什麼變化?」 – Legonaftik