ios - 快速设置 UiCollectionView 中单元格的选定颜色

标签 ios swift

我正在使用 collectionview 来显示数据。

每个单元格选中和未选中的颜色都在那里

但我想在 collectionview 中设置第一个单元格的默认颜色。

enter image description here

如果有10条数据。我的第一个单元格应该像屏幕截图中那样

如何实现? 当我在索引路径中设置颜色时,会出现此问题

enter image description here

最佳答案

对于基于单元格选定状态的两种不同颜色,您可能需要像这样子类您的 UICollectionViewCell:

import UIKit 

class YourCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView! // for example - some UI element inside cell ...

    override var isSelected: Bool {
        didSet {
            self.contentView.backgroundColor = isSelected ? UIColor.blue : UIColor.yellow
            self.imageView.alpha = isSelected ? 0.75 : 1.0
        }  
      }
    }


// and below you will have your original code

class YourViewController: UICollectionViewController {

... etc

回答您的问题 - 第一个单元格的特殊样式:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell ... 

        if(indexPath.row == 0) { //for first cell in the collection
            cell.backgroundColor = UIColor.orange
        } else {
            cell.backgroundColor = UIColor.green
        }

关于ios - 快速设置 UiCollectionView 中单元格的选定颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39293072/

相关文章:

iphone - 在 iPhone 中记录来自蓝牙耳机的输入

ios - Xcode iOS bundle 包含不允许的文件 'Frameworks'

ios - 如何为我的应用程序创建服务条款页面

ios - swift 3 触发容器 View 内容更新

swift - 在 Examples.xcworkspace 中执行示例应用程序时遇到问题,XCode 尝试一次执行所有示例应用程序

ios - 当 alpha 值不是 1 或 0 时,Metal MTLTexture 会用黑色替换半透明区域

ios - 去除搜索栏黑色边框

ios - Quickblox ipv6 支持

ios - 在不使用 for 循环的情况下更新字典数组中的键值对

ios - 未调用 Flutter Firebase Messaging iOS 处理程序