根据您的问题,我假设您只有一个选定的学生,我用一组用户可以选择的图标做了类似的事情。
首先,我确实加载了:
override func viewDidLoad() {
super.viewDidLoad()
iconCollectionView.delegate = self
iconCollectionView.dataSource = self
iconCollectionView.allowsMultipleSelection = false
iconCollectionView.selectItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), animated: false, scrollPosition: .None)
}
这里我默认选择第一个单元格,您可以使用StudentArray.indexOf 来获取您选择的学生索引。然后显示我选择了哪个项目:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = iconCollectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! IconCollectionViewCell
cell.imageView.image = UIImage(named: imageResourceNames.pngImageNames[indexPath.row])
if cell.selected {
cell.backgroundColor = UIColor.grayColor()
}
return cell
}
当集合首次显示时调用,然后对选择的变化做出反应:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.cellForItemAtIndexPath(indexPath)?.backgroundColor = UIColor.grayColor()
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.cellForItemAtIndexPath(indexPath)?.backgroundColor = UIColor.clearColor()
}
显然有很多方法可以显示单元格选择,我的方法很简单,但这就是我需要做的。
编辑:自从发布上述内容后,我意识到在单元类中向selected 添加观察者更简单:
class IconCollectionViewCell: UICollectionViewCell {
...
override var selected: Bool {
didSet {
backgroundColor = selected ? UIColor.grayColor() : UIColor.clearColor()
}
}
}
有了这个,就不需要处理didSelect 或didDeselect 或检查cellForItemAtIndexPath 中的选择,单元格会自动执行。