Created
March 22, 2022 09:48
-
-
Save KrauserHuang/c1eae831f1b4d2e42bdd85202b61926d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct CategoryCellModel { //CellModel儲存category跟isSelected參數 | |
let category: Category | |
var isSelected: Bool = false | |
} | |
var categories = [CategoryCellModel]() { | |
didSet { | |
DispatchQueue.main.async { | |
self.categoryCollectionView.reloadData() | |
} | |
} | |
} | |
func setProductType() { | |
ProductService.shared.loadProductType(id: user.member_id, pwd: user.member_pwd) { responseCategories in | |
//新增isFirstCategory,map後將responseCategories的第一個項目isSelected設成true | |
var isFirstCategory = true | |
self.categories = responseCategories.map { | |
if isFirstCategory { | |
//第一個項目會跑到這裡,之後因為isFirstcategory == false,所以不會設到isSelected狀態(false) | |
isFirstCategory = false | |
return CategoryCellModel(category: $0, isSelected: true) | |
} else { | |
return CategoryCellModel(category: $0) | |
} | |
} | |
} | |
} | |
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 //isItemSelected是cell對應isSelected true/false進行UI變動 | |
//從這裡因為category[0].isSelected == true,所以會變更UI外觀 | |
return item | |
} | |
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { | |
for (index, _) in categories.enumerated() { | |
//當index與indexPath.item有對應到,isSelected = true,狀態改變 | |
categories[index].isSelected = index == indexPath.item | |
} | |
} | |
//Cell的property | |
var isItemSelected: Bool = false { | |
didSet { | |
indicatorView.alpha = isItemSelected ? 1 : 0 | |
categoryLabel.textColor = isItemSelected ? UIColor(hex: "#5F9EA0") : .systemGray2 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment