Bronze Challenge: Cell Colors


#1

I made the things simple, affecting only the viewController, I added 2 methods;

func isBiggerThan50(value: Int)
-> Bool{
    if(value > 50){
        return true
    }
    return false
}

func colorOfValue(cell: ItemCell, bigger50: Bool) ->  Void {

    if(bigger50){
        cell.valueLabel.textColor = UIColor.red
    }else{
        cell.valueLabel.textColor = UIColor.green
    }
}

And after that i invoke the 2nd in the cellForRowAt method:

   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell",for: indexPath ) as! ItemCell
    let item = itemStore.allItems[indexPath.row]
    cell.nameLabel.text = item.name
    cell.valueLabel.text = "$" + String(item.valueInDollars)
    cell.serialNumberLabel.text = item.serialNumber
    colorOfValue(cell: cell, bigger50: isBiggerThan50(value: item.valueInDollars))
    return cell;
}   

It’s done!


#2

The Bronze Challenge mentions

Update the ItemCell

Almost all the answers seem to update the ItemsViewController cellForRowAt method.
I have figured out a way to update the label colors in the ItemCell itself.
This uses a number formatter to get the value out of the currency string.

class ItemCell: UITableViewCell {

    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var serialNumberLabel: UILabel!
    @IBOutlet var valueLabel: ValueLabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // Also available in Attributes Inspector > Dynamic Type > Automatically Adjusts Font
        nameLabel.adjustsFontForContentSizeCategory = true
        serialNumberLabel.adjustsFontForContentSizeCategory = true
        valueLabel.adjustsFontForContentSizeCategory = true
    }
}

class ValueLabel: UILabel {
    
    override var text: String? {
        didSet {
            if let validText = text {
                let formatter = NumberFormatter()
                formatter.numberStyle = .currency
                formatter.locale = Locale(identifier: "en_us")
                
                if let value = formatter.number(from: validText) {
                    let amount = value.intValue
                    if amount >= 50 {
                        textColor = UIColor.red
                    }
                    else if amount < 50 {
                        textColor = UIColor.green
                    }
                }
                else {
                    textColor = UIColor.darkText
                }
            }
        }
    }
}

#3

I like the solution of making changes from within ItemCell.swift. I went with the first solution that came to mind. A friend showed me how to use “Color Literals,” which I think are pretty cool: