swift - 如何在 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
为粉色、黄色、绿色、蓝色..
如何?请指导我
解决方案
最好的方法是使用 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]
推荐阅读
- powershell - 使用 Powershell 更改 SERVER 的 Home FTP SSL 证书
- c++ - 如何在按下按钮滚动文本时中断 LED 矩阵?(阿杜诺)
- heroku - 在容器中部署时 Heroku 进程以状态 1 退出
- r - 具有相同名称的多个集合的 pivot_longer_to
- java - 即使构建成功,“Maven 依赖项”文件夹也丢失
- angular - 在 Highchart 的向下钻取函数中访问 Angular 类级别数据
- javascript - 为什么我的 JS API 客户端每行输出返回一个文件,而不是单个文件?
- amazon-web-services - AWS Codebuild & Cloudfront:构建后测试部署
- express - 由于第三方 cookie 阻止,CSRF 保护在 Safari 浏览器中不起作用
- javascript - 未捕获的 ReferenceError:未定义 toastr