Reputation: 5426
I have a UICollectionView
that has the same cell type, but every cell has different UI properties like background color
, textColor
...
I could configure them inside collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
as below:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = indexPath.item
switch item {
case 1:
let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as ACollectionViewCell
cell.ScoreName.text = xxx
cell.ScoreName.textColor = xxx
cell.score.text = xxx
cell.score.backgroundColor = xxx
cell.....
return cell
case 2: ...
case 3: ...
case 4: ...
case 5: ...
case 6:
let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as BCollectionViewCell
cell.title.text = "xxx xxx"
cell.score.isHidden = true
return cell
default:
let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as DCollectionViewCell
cell.title.text = "xxx"
cell.score.text = "xx"
cell.score.backgroundColor = .green
cell....
return cell
}
}
As you can see from case 1 to 5 same cell type with different UI properties, it is not appealing at all also it is not scalable so what is the best approach to deal with such configuration ?
Upvotes: 0
Views: 80
Reputation: 3657
You need keep data in memory so you have to store the configuration of cell due to reusable nature of UICollectionViewCell
.
let dictForCell = ["color":UIColor.redColor(),"isHidden":false] //add key value according to your need
let arrOfCell = [dictForCell] //also add dictionary of detail
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let dictData = [indexPath.row]
let cell = collectionView.dequeueReusableCell(forIndexPath: indexPath) as ACollectionViewCell
cell.ScoreName.textColor = dictData["color"] as! UIColor
cell.score.isHidden = dictData["color"] as! Bool
cell.score.text = xxx
cell.score.backgroundColor = xxx
cell.ScoreName.text = xxx
return cell
}
Upvotes: 1
Reputation: 3362
background color, textColor, etc. should be added as variables in the object you use to populate that collection view. Each object will have its own variables which will be used to customize the cell.
Upvotes: 0