私はUICollectionViewControllerのサブクラスを実装しました。これは水平方向にスクロール可能です。そのアイテムを1つだけ選択できるようにします。UICollectionViewController内のアイテムを1つだけ選択してください
現在の画面で選択した項目を変更すると問題なく動作します。ただし、たとえば、コレクションの最初の部分でアイテムを選択し、次に右にスクロールして別のアイテムを選択すると、最初のアイテムが選択されます。
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
}
}
は私が間違って何をやっている:
ここでは私のCollectionViewの現在のバージョンがありますか?
クールは、それが私を助けてくれ!しかし、なぜ 'super.isSelected = newValue'を呼び出さなければならないのか説明できますか?このコード行を削除しても私のプログラムでは何も変更されません – Legonaftik
何も変更しないと、この行を削除してもプログラムが動作しないということですか? – PGDev
いいえ、コードを使用するとすべて正常に動作します。 'super.isSelected = newValue'行を削除しても、すべてが動作します。だから問題は、「なぜ私はこの行を書かなければならないのですか? – Legonaftik