滚动Swift时表视图单元格更改颜色 [英] Table View Cells changing colors when scrolling Swift

查看:132
本文介绍了滚动Swift时表视图单元格更改颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.当用户滚动了一下时:

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.

推荐答案

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

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
 }

这篇关于滚动Swift时表视图单元格更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆