Question


Setup


  1. Register your collection view cell(I use storyboard + XIB)
  2. Basic collection view delegate/datasource method
  3. Connect your UI(IBOutlet) into collection view cell

CellModel


<aside> 💡 Here because I’m not familiar with model, so didn’t come up with this solution first

</aside>

  1. Create CategoryCellModel

    struct CategoryCellModel {
        let category: **Category**
        var isSelected: Bool = false
    }
    
  2. Change your property to this new model struct

    var categories = [**CategoryCellModel**]() {
        didSet {
            DispatchQueue.main.async {
                self.categoryCollectionView.reloadData()
            }
        }
    }
    
  3. Configure your data status(Here you set the first one isSelected to true)

    ProductService.shared.loadProductType(id: user.member_id, pwd: user.member_pwd) { responseCategories in
        var **isFirstCategory** = true
        self.categories = responseCategories.**map** {
            if isFirstCategory {
                isFirstCategory = false
                return **CategoryCellModel(category: $0, isSelected: true)**
            } else {
                return **CategoryCellModel(category: $0)**
            }
        }
    }
    
  4. Set isItemSelected property for collection view cell

    var isItemSelected: Bool = false {
        didSet {
            indicatorView.alpha = isItemSelected ? 1 : 0
            categoryLabel.textColor = isItemSelected ? UIColor(hex: "#5F9EA0") : .systemGray2
        }
    }
    
  5. Update your cellForItemAt method

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let item = categoryCollectionView.dequeueReusableCell(withReuseIdentifier: CategoryCollectionViewCell.reuseIdentifier, for: indexPath) as? CategoryCollectionViewCell else {
            return UICollectionViewCell()
        }
        let category = categories[indexPath.row]
        item.configure(with: category)
        **item.isItemSelected = category.isSelected**
    
        return item
    }
    
  6. Add style change on didSelectItemAt

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // UI
        **for (index, _) in categories.enumerated() {
            categories[index].isSelected = index == indexPath.item
        }**
    }
    

Result