Table View Cells changing colors when scrolling Sw

2019-06-28 07:41发布

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.

1条回答
Anthone
2楼-- · 2019-06-28 08:14

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
 }
查看更多
登录 后发表回答