Search code examples
swiftuitableviewcolorscell

How to give 4 different colours for each cell in tableview in swift


I am using tableview to show data.. i have only one section and rows coming according to JSON response count

here i am using four colours (pink, yellow, green, blue) for cell view background colour

present i am able to show all cells in one colour(yellow).. now i need to show each cell in 4 (pink, yellow, green, blue) colours

i mean if there are two cells then i need to show cell background colour one cell in pink and other in yellow

if there r 4 cells then 4 cells background colour in pink, yellow, green, blue

if there r 8 cells then first 4 cells in pink, yellow, green, blue colour and then next 4 cells in pink, yellow, green, blue colour

like this..

code for tableview cells:

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

}

here present all cells showing in yellow colour cell.catView.backgroundColor = .yellow but i need to change cell.catView.backgroundColor in pink, yellow, green, blue colours..

how? please do guide me


Solution

  • Best way to do it would be to use to % operator. It will get the remainder and correlate that to a color.

    It will look something like this

    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
    }
    

    Alternatively, you can store all the colors in an array and use the % in that.

    let colors: [UIColor] = [.yellow, .pink, .green, .blue]
    cell.catView.backgroundColor = colors[indexPath.row % colors.count]