register
numberOfItemsInSection
cellForItemAt
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)
return item
}
didSelectItemAt
<aside> 💡 Here because I’m not familiar with model, so didn’t come up with this solution first
</aside>
Create CategoryCellModel
struct CategoryCellModel {
let category: **Category**
var isSelected: Bool = false
}
Change your property to this new model struct
var categories = [**CategoryCellModel**]() {
didSet {
DispatchQueue.main.async {
self.categoryCollectionView.reloadData()
}
}
}
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)**
}
}
}
Set isItemSelected property for collection view cell
var isItemSelected: Bool = false {
didSet {
indicatorView.alpha = isItemSelected ? 1 : 0
categoryLabel.textColor = isItemSelected ? UIColor(hex: "#5F9EA0") : .systemGray2
}
}
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
}
Add style change on didSelectItemAt
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// UI
**for (index, _) in categories.enumerated() {
categories[index].isSelected = index == indexPath.item
}**
}