ios - Swift:UICollectionViewCell didSelectItemAtIndexPath 改变背景颜色

标签 ios swift uicollectionview uicollectionviewcell

我可以很容易地在 CellForItemAtIndexPath 方法中更改单元格的背景颜色

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath     indexPath: NSIndexPath) -> UICollectionViewCell {
 cell.backgroundColor = UIColor.blackColor()
 }

但是,当我尝试更改 DidSelectItemAtIndexPath 中的颜色时,它不起作用。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath     indexPath: NSIndexPath) {
        let cell: ButtonCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCollectionCell {
cell.backgroundColor = UIColor.blackColor()

另外我在某处读到,使用 didSelectItemAtIndexPath 将不起作用,因为一旦 Collection View 开始滚动,颜色就会变回

Swift 中的修复是什么?

非常感谢您的帮助

最佳答案

你可以使用这个方法:

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){

    var cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
    cell.backgroundColor = UIColor.magentaColor()
}

关于ios - Swift:UICollectionViewCell didSelectItemAtIndexPath 改变背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28596859/

相关文章:

ios - soundcloud iOS 加密

ios - UINavigationController 中的 UIPageController 偏离顶部?

swift - View Controller 未正确显示

ios - JSQMessagesView 动画行高变化的问题

ios - CollectionView 不使用 DKImagePickerController 重新加载

ios - 如何在SupplementaryView 上用tabbar 布局UICollectionView,并切换不同的内容?

ios - 添加环境变量会影响 iOS 上的应用程序速度吗?

ios - 过滤 UItableview Swift IOS

swift - GCD swift 4 线程安全

ios - 用户无法删除追加后提交的文本中的字符