如何在 swift 中为 tableview 中的每个单元格提供 4 种不同的颜色

Posted

技术标签:

【中文标题】如何在 swift 中为 tableview 中的每个单元格提供 4 种不同的颜色【英文标题】:How to give 4 different colours for each cell in tableview in swift 【发布时间】:2021-08-23 05:02:59 【问题描述】:

我正在使用 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 更改为粉色、黄色、绿色、蓝色......

怎么样?请指导我

【问题讨论】:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 中添加您的自定义颜色逻辑 - 您可以使用indexPath 读取索引路径(单元格的索引)。 if indexPath.row == 0 else if indexPath.row == 1 ... 【参考方案1】:

最好的方法是使用% 运算符。它将获取余数并将其与颜色相关联。

它看起来像这样

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]

【讨论】:

不要忘记defaultswitch 声明中:D【参考方案2】:

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

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
    

【讨论】:

以上是关于如何在 swift 中为 tableview 中的每个单元格提供 4 种不同的颜色的主要内容,如果未能解决你的问题,请参考以下文章

如何在 swift 中的 tableview 中的 numberOfRowsInSection 中比较和显示不同的数组计数

如何在 Swift 中为 UITableView 设置左右边距

iOS - 在视图(Swift)中为多个Tableview或Collectionviews使用/传递手势识别器

如何在 Xcode 中为我的表格视图添加上边距?

如何在 Swift 中使用 MagicalRecord CoreData 删除 tableview 中的记录

如何在 swift 中更改 tableView 部分中的文本颜色