首页 > 解决方案 > 如何在 swift 中为 tableview 中的每个单元格提供 4 种不同的颜色

问题描述

我正在使用 tableview 来显示数据.. 根据 JSON 响应计数,我只有一个部分和行

这里我使用四种颜色(粉色、黄色、绿色、蓝色)作为单元格视图背景颜色

目前我能够以一种颜色(黄色)显示所有单元格。现在我需要以 4 种颜色(粉色、黄色、绿色、蓝色)显示每个单元格

我的意思是如果有两个单元格,那么我需要显示单元格背景颜色,一个单元格为粉红色,另一个为黄色

如果有 r 4 个单元格,则 4 个单元格背景颜色为粉红色、黄色、绿色、蓝色

如果有 r 8 个单元格,则前 4 个单元格为粉色、黄色、绿色、蓝色,然后接下来 4 个单元格为粉色、黄色、绿色、蓝色

像这样..

表格视图单元格的代码:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.homeData?.result?.recents?.count ?? 0
}

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "HomePostsTableViewCell", for: indexPath) as! HomePostsTableViewCell
cell.selectionStyle = .none

cell.catView.backgroundColor = .yellow
cell.categoryLabel.text = category

return cell

}

这里展示了所有显示为黄色的单元格,cell.catView.backgroundColor = .yellow但我需要更改cell.catView.backgroundColor为粉色、黄色、绿色、蓝色..

如何?请指导我

标签: swiftuitableviewcolorscell

解决方案


最好的方法是使用 to%运算符。它将获得剩余部分并将其与颜色相关联。

它看起来像这样

switch indexPath.row % 4 {
case 0:
       cell.catView.backgroundColor = .yellow
case 1:
       cell.catView.backgroundColor = .pink
case 2:
       cell.catView.backgroundColor = .green
case 3:
       cell.catView.backgroundColor = .blue
}

或者,您可以将所有颜色存储在一个数组中并%在其中使用。

let colors: [UIColor] = [.yellow, .pink, .green, .blue]
cell.catView.backgroundColor = colors[indexPath.row % colors.count]

推荐阅读