我正在使用tableview来显示数据。根据JSON响应计数,我只有一个部分和行
这里我使用四种颜色(粉红色,黄色,绿色,蓝色)作为细胞视图背景颜色。
现在我可以用一种颜色(黄色)显示所有的细胞。现在我需要用4种颜色显示每个单元格(粉红色,黄色,绿色,蓝色)。
我的意思是,如果有两个细胞,那么我需要显示细胞背景颜色,一个是粉红色,另一个是黄色。
如果有r4细胞,则4个细胞的背景颜色为粉红色、黄色、绿色、蓝色。
如果有r8细胞,则前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更改为粉红色、黄色、绿色、蓝色。
多么?请指点我
发布于 2021-08-23 05:10:44
最好的方法是使用%操作符。它将得到剩余部分,并将其与颜色相关联。
它会看起来像这样
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]发布于 2021-08-23 05:09:42
您可以在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
}https://stackoverflow.com/questions/68887535
复制相似问题