5

我正在制作一个使用彩色表格视图单元格将其他单元格分成类别的应用程序。我通过使用 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
    }


}

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

与用户滚动一点时相比: 滚动后

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

4

1 回答 1

2

您可以在 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
 }
于 2016-07-20T13:31:38.710 回答