marrioa
marrioa

Reputation: 1275

table view cell selection color works after 0 cell but not first row?

I changed the tableview cell selection color and it works well only from row 1 and beyond but row 0 "first"doesn't it shows the default light gray color .

Is the way I did wrong?

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)



    // Configure the cell...

    let colorView = UIView()
    let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0)
    colorView.backgroundColor = green
    UITableViewCell.appearance().selectedBackgroundView = colorView


        cell.textLabel?.text = "#" + books[indexPath.row]

        return cell
     }

Upvotes: 1

Views: 95

Answers (2)

Sergii Martynenko Jr
Sergii Martynenko Jr

Reputation: 1407

Do you realise, that you change all cells appearance with this call UITableViewCell.appearance().selectedBackgroundView = colorView? So, each time your table view asks for one cell, you create new view, call it colorView and replace the selectedBackgroundView for all previously created cells? You're doing it wong.

Move this

let colorView = UIView()
let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0)
colorView.backgroundColor = green
UITableViewCell.appearance().selectedBackgroundView = colorView

to your viewDidLoad method.

But, it is ok only if you need not just green colour for selected cell, but something more complicated.

Better do this in your cellForRowAtIndexPath

cell.selectedColor = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0)

Upvotes: 1

Lukas
Lukas

Reputation: 3433

If you just wanna change the background color, you don't need to create a UIView and set background color to it. instead change the contentView background and it should be in the didSelectRow... method. not in cellForRow.. as that is for the table view to load every single cell

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let green = UIColor(red:0.31, green:0.62, blue:0.53, alpha:1.0)
    tableView.cellForRowAtIndexPath(indexPath)?.contentView.backgroundColor = green 
}

Upvotes: 1

Related Questions