首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何快速地为桌面上的每个单元格提供4种不同的颜色

如何快速地为桌面上的每个单元格提供4种不同的颜色
EN

Stack Overflow用户
提问于 2021-08-23 05:02:59
回答 2查看 686关注 0票数 1

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

这里我使用四种颜色(粉红色,黄色,绿色,蓝色)作为细胞视图背景颜色。

现在我可以用一种颜色(黄色)显示所有的细胞。现在我需要用4种颜色显示每个单元格(粉红色,黄色,绿色,蓝色)。

我的意思是,如果有两个细胞,那么我需要显示细胞背景颜色,一个是粉红色,另一个是黄色。

如果有r4细胞,则4个细胞的背景颜色为粉红色、黄色、绿色、蓝色。

如果有r8细胞,则前4个细胞为粉红色、黄色、绿色、蓝色,然后4个细胞为粉红色、黄色、绿色、蓝色。

像这样..。

表视图单元格代码:

代码语言:javascript
复制
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更改为粉红色、黄色、绿色、蓝色。

多么?请指点我

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-08-23 05:10:44

最好的方法是使用%操作符。它将得到剩余部分,并将其与颜色相关联。

它会看起来像这样

代码语言:javascript
复制
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
}

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

代码语言:javascript
复制
let colors: [UIColor] = [.yellow, .pink, .green, .blue]
cell.catView.backgroundColor = colors[indexPath.row % colors.count]
票数 3
EN

Stack Overflow用户

发布于 2021-08-23 05:09:42

您可以在cellForRowAt方法中添加此逻辑。

代码语言:javascript
复制
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: "HomePostsTableViewCell", for: indexPath) as! HomePostsTableViewCell
    cell.selectionStyle = .none
    
    switch indexPath.row % 4 {
    case 0:
        cell.catView.backgroundColor = .systemPink
    case 1:
        cell.catView.backgroundColor = .yellow
    case 2:
        cell.catView.backgroundColor = .green
    case 3:
        cell.catView.backgroundColor = .blue
    default: break
    }
    
    cell.categoryLabel.text = category
    
    return cell
    
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68887535

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档