我有一个作为 UICollectionViewController 实现的滑出式菜单。我也为 Collection View 创建了自定义单元格。导航和一切都按预期工作。我遇到的问题是当我点击一个实际的单元格时改变单元格的外观。
我已经尝试了几种基于解决方案的方法( 1 )( 2 ) 我在堆栈上看到过,但没有令我满意的地方。
解决方案 1:实现 UICollectionViewController 委托(delegate)方法:
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()
}
}
当我尝试这个解决方案时,没有任何反应。单元格背景颜色不会改变颜色。
解决方案 2:除了当我按住单元格时,打开的单元格会改变颜色外,此解决方案会产生更好的结果。我希望单元格背景颜色在点击 时快速闪烁或突出显示,而不仅仅是在用户按住单元格时。
class SlideOutMenuCells: UICollectionViewCell {
//Setup code...
override var isHighlighted: Bool {
didSet {
if self.isHighlighted {
backgroundColor = UIColor.darkGreen()
} else {
backgroundColor = UIColor.mainGreen()
}
}
}
}
这两种解决方案都没有真正按预期工作。我在这里看到了几篇尝试解决这个问题的帖子,但还没有找到真正有效的解决方案。我希望单元格通过点击闪烁突出显示,而不仅仅是当用户单击并按住单元格时...
最佳答案
这是突出显示的工作代码 UICollectionViewCell
点击(swift 4 | swift 5)
解决方案一
class StoreCollViewCell:UICollectionViewCell{
override var isSelected: Bool {
didSet {
self.contentView.backgroundColor = isSelected ? UIColor.red : UIColor.clear
}
}
}
方案二
不需要在您的 UICollectionViewCell
类中执行任何操作。
class StoreListViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
var previousSelected : IndexPath?
var currentSelected : Int?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "StoreCollViewCell", for: indexPath) as! StoreCollViewCell
// To set the selected cell background color here
if currentSelected != nil && currentSelected == indexPath.row
{
cell.backgroundColor = UIColor.green
}else{
cell.backgroundColor = UIColor.yellow
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// For remove previously selection
if previousSelected != nil{
if let cell = collectionView.cellForItem(at: previousSelected!){
cell.backgroundColor = UIColor.yellow
}
}
currentSelected = indexPath.row
previousSelected = indexPath
// For reload the selected cell
self.collVwStores.reloadItems(at: [indexPath])
}
}
输出
关于ios - 点击时突出显示 uicollectionview 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52099360/