我有一个UICollectionView
,它显示了从网络接收的内容。单元数只能在运行时知道。客户要求收集视图中的每一行必须具有不同的颜色。
例如,如果我必须在UICollectionView
中显示12个项目,则假设第一行有3个单元格,则所有三个单元格的颜色都应为红色。
第二行的单元格应为白色,依此类推。
您能帮我实现它吗?
谢谢。
答案 0 :(得分:1)
在cellForRowAt
上,如果要插入颜色,则可以检查indexPath.row并更新背景颜色。
if indexPath.item % 2 == 0 {
<#YourCell#>.backgroundColor = .blue
} else {
<#YourCell#>.backgroundColor = .green
}
此外,如果您想要随机的颜色,则可以检查以下答案:How to make a random color with Swift
然后,您只需设置<#YourCell#>.backgroundColor
随机颜色
在collectionViewCell在每个单元格上都有另一个collectionView的情况下,并且必须为每个父collectionView行匹配相同的颜色,我建议您为父collectionView单元格创建一个自定义类,以便每个collectionView子行可以使用它并设置它自己的backgroundColor。
答案 1 :(得分:0)
更新的答案:
我假设您最初具有以下变量:
private let cellBackgroundColors: [UIColor] = [.yellow, .green, .blue, .purple]
private let numberOfRows = 3 (or you can assign it dynamically)
第二步,像这样实现:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ToDoListCollectionCell
let index = indexPath.item / numberOfRows
if index < cellBackgroundColors.count {
cell.backgroundColor = cellBackgroundColors[index]
} else {
cell.backgroundColor = .white // Set your default color to handle this case
}
return cell
}
快乐编码!