【发布时间】:2017-05-26 15:47:48
【问题描述】:
我已经实现了 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
}
}
我做错了什么?
【问题讨论】:
标签: ios swift uicollectionview