Avinash Mishra
Avinash Mishra

Reputation: 797

How Do I change UITableViewCell Colour According to Array in Same Section Swift 4

I have Two Array of Int In which the Index Number is Stored and I want that IndexPath.row cell Background Colour Should Change accordingly.

let   redCell     = ["0","1","4"]
let   greenCell   = ["2","3"]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var  cell  = tableView.dequeueReusableCell(withIdentifier: "playQuizTableViewCell") as? playQuizTableViewCell

    if indexPath.row == redCell {
        cell?.textLabel?.backgroundColor = UIColor.red
    } else if indexPath.row == greenCell{
        cell?.textLabel?.backgroundColor = UIColor.green
    } else {
        cell?.textLabel?.backgroundColor = UIColor.black
    }
}

I want to change cell colour of indexPath.row which is matching inside the array.

Please Guide me. Thanks

Upvotes: 0

Views: 206

Answers (1)

rmaddy
rmaddy

Reputation: 318774

First, make your arrays into arrays of Int instead of String.

let redCell = [0, 1, 4]
let greenCell = [2, 3]

Now update your cellForRowAt to check if indexPath.row is in a given array:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier: "playQuizTableViewCell") as! playQuizTableViewCell

    if redCell.contains(indexPath.row) {
        cell.textLabel?.backgroundColor = .red
    } else if greenCell.contains(indexPath.row) {
        cell.textLabel?.backgroundColor = .green
    } else {
        cell?.textLabel?.backgroundColor = .black
    }
}

Upvotes: 4

Related Questions