突出显示uicollectionview单元格

muf*_*ufc 9 ios uicollectionview uicollectionviewcell swift

我有一个滑出菜单,我已经实现为UICollectionViewController.我也为集合视图创建了自定义单元格.导航和一切按预期工作.我遇到麻烦的是当我点击一个实际的细胞时改变细胞外观.

我已经尝试了几种基于解决方案的方法(1)(2)我在堆栈上看过但没有让我满意.

解决方案1:实现UICollectionViewController委托方法:

class SlideOutMenuViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout{
   //Setup code and other delegate methods….

    override func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SlideOutMenuCells

        cell.backgroundColor = .white
    }

    override func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SlideOutMenuCells

        cell.backgroundColor = UIColor.mainGreen()
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试这个解决方案,没有任何反应.单元格背景颜色不会改变颜色.

解决方案2:此解决方案产生更好的结果,除了当我按住单元格时单元格会改变颜色.我希望单元格的背景颜色能够在点击时快速闪烁或突出显示,而不仅仅是用户按住单元格.

class SlideOutMenuCells: UICollectionViewCell {

    //Setup code...

    override var isHighlighted: Bool {
        didSet {
            if self.isHighlighted {
                backgroundColor = UIColor.darkGreen()
            } else {
                backgroundColor = UIColor.mainGreen()
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

两种解决方案都没有按预期工作.我在这里看过几篇试图解决这个问题的帖子,但没有找到一个真正有效的解决方案.我希望单元格能够通过点按来突出显示,而不仅仅是当用户点击并按住单元格时......

Kev*_*ers 12

我遇到了完全相同的问题,解决方案实际上比上面发布的要简单得多。

在您的视图控制器中,添加collectionView.delaysContentTouches = false.

然后你在单元格中的其他代码很好:

class SlideOutMenuCells: UICollectionViewCell {

    //Setup code...

    override var isHighlighted: Bool {
        didSet {
            if self.isHighlighted {
                backgroundColor = UIColor.green
            } else {
                backgroundColor = UIColor.red
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是现在烦人的延迟消失了!


Nik*_*ani 8

这是用于突出显示的工作代码 UICollectionViewCell (swift 4)

你的UICollectionViewCell班级不需要做任何事情.

class StoreCollViewCell:UICollectionViewCell{

    override var isSelected: Bool {
        didSet {
            self.contentView.backgroundColor = isSelected ? UIColor.red : UIColor.clear
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

在此输入图像描述

在此输入图像描述