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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With