Swift 表格视图单元格在快速滚动时更改颜色

Swift 表格视图单元格在快速滚动时更改颜色,swift,uitableview,colors,cell,visual-glitch,Swift,Uitableview,Colors,Cell,Visual Glitch,我正在制作一个应用程序,它使用彩色表格视图单元格将其他单元格划分为不同的类别。我通过使用if-else语句为单元格着色来实现这一点。但出于某种原因,当我启动应用程序时,我在表格视图上上下滚动的次数越多,其他单元格随机改变颜色的次数也越多。这是我的自定义instrumentTableCell类中的代码: @IBOutlet var nameLabel: UILabel? @IBOutlet var descriptionLabel: UILabel? @IBOutlet var thumbnail

我正在制作一个应用程序,它使用彩色表格视图单元格将其他单元格划分为不同的类别。我通过使用if-else语句为单元格着色来实现这一点。但出于某种原因,当我启动应用程序时,我在表格视图上上下滚动的次数越多,其他单元格随机改变颜色的次数也越多。这是我的自定义instrumentTableCell类中的代码:

@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
    }


}
这就是应用程序启动时的样子:

与用户滚动一点时的情况相比:


另外,如果有人知道怎么做,我希望彩色单元格也更小,这样应用程序看起来更漂亮。

您可以在cellForRowAtIndexPath委托方法中设置

  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
 }

向我们展示
cellForRowAtIndexPath:
method的内容这是因为单元格是重复使用的。如果nameLabel!则在
之后执行!。text==“可选加载项”{backgroundColor=UIColor.cyanColor()}
do
else{backgroundColor=UIColor.clearColor()}
(或whiteColor())@Larme谢谢你的帮助!