Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table View Cells changing colors when scrolling Swift

I'm making an app that uses colored table view cells to separate other cells into categories. I am doing this by coloring the cells different colors using if else statements. But for some reason, when I launch the app, the more I scroll up and down on the table view, the more other cells randomly change color too. This is the code in my custom instrumentTableCell class:

@IBOutlet var nameLabel: UILabel?
@IBOutlet var descriptionLabel: UILabel?
@IBOutlet var thumbnailImage: UIImageView!

func configurateTheCell(recipie: Recipie) {
    self.nameLabel?.text = recipie.name
    self.descriptionLabel?.text = recipie.description
    self.thumbnailImage?.image = UIImage(named: recipie.thumbnails)
    if nameLabel!.text == "Instrument"
    {
        backgroundColor = UIColor.orangeColor()
        nameLabel?.textColor = UIColor.blackColor()
    }
    else if nameLabel!.text == "Optional addon"
    {
        backgroundColor = UIColor.cyanColor()
    }

}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if nameLabel!.text == "Instrument"
    {
        return 20
    }
    else if nameLabel!.text == "Optional addon"
    {
        return 20
    }
    else
    {
        return 100
    }


}

and this is what the app looks like when launched: when the app is launched

vs. when the user has scrolled around a little bit: after scrolled around

also if anyone knows how, I would like the colored cells to also be smaller so the app looks nicer.

like image 526
zach2161 Avatar asked Oct 30 '22 23:10

zach2161


1 Answers

You can set in cellForRowAtIndexPath delegate method

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("your identifier", forIndexPath: indexPath)
     if cell.recipie.name == "Instrument"
     {
      backgroundColor = UIColor.orangeColor()
      nameLabel?.textColor = UIColor.blackColor()
     }
    else if cell.recipie.name == "Optional addon"
     {
      backgroundColor = UIColor.cyanColor()
     }
   else{
    backgroundColor = UIColor.whiteColor()
   }
  return cell
 }
like image 50
Subin K Kuriakose Avatar answered Nov 15 '22 07:11

Subin K Kuriakose