【发布时间】: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