Table View Cells changing colors when scrolling Swift

我的未来我决定 提交于 2019-12-10 17:37:45

问题


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:

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

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


回答1:


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
 }


来源:https://stackoverflow.com/questions/38482561/table-view-cells-changing-colors-when-scrolling-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!