【问题标题】:How to give 4 different colours for each cell in tableview in swift如何在 swift 中为 tableview 中的每个单元格提供 4 种不同的颜色
【发布时间】: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 { } ...

标签: swift uitableview colors cell


【解决方案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
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2017-02-18
    • 2017-01-05
    • 2015-07-02
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    相关资源
    最近更新 更多