How to change background color of cell in swift

I am new to swift but I am wondering how to change the cell color of a tableView. My project is to change the cell color and name to whatever the RGB values are on the slider. However, every attempt I try it ruins my text. It makes it not bold and half broken. I have posted picture examples. I used cell.textLabel?.backgroundColor and cell.backgroundColor yet those dont work. Any Ideas?

class EditCustomColors: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var RedLabel: UILabel!

    @IBOutlet weak var GreenLabel: UILabel!
    @IBOutlet weak var BlueLabel: UILabel!
    @IBOutlet weak var RedSlider: UISlider!
    @IBOutlet weak var GreenSlider: UISlider!
    @IBOutlet weak var BlueSlider: UISlider!
    @IBOutlet weak var DisplayingLabel: UILabel!

    @IBOutlet weak var tableView: UITableView!

    var cellRow: Int = 0

    var colorName: [String] = []

    var RedColor : Float = 0
    var GreenColor : Float = 0
    var BlueColor : Float = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self

        let colorNameDefault = UserDefaults.standard
        if(colorNameDefault.value(forKey: "ColorNames") != nil){
            colorName = colorNameDefault.value(forKey: "ColorNames") as! [String]
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func RedSliderAction(sender: UISlider) {
        ChangeColors()
    }

    @IBAction func GreenSliderAction(sender: UISlider) {
        ChangeColors()
    }

    @IBAction func BlueSliderAction(sender: UISlider) {
        ChangeColors()
    }

    func ChangeDisplayLabelColor(){
        DisplayingLabel.backgroundColor = UIColor(red: CGFloat(RedColor), green: CGFloat(GreenColor), blue: CGFloat(BlueColor), alpha: 1.0)
        changeLabelNumbers()
    }

    func ChangeColors(){
        RedColor = RedSlider.value
        GreenColor = GreenSlider.value
        BlueColor = BlueSlider.value
        ChangeDisplayLabelColor()
    }

    func changeLabelNumbers(){
        let RoundedRed = String(format: "%0.0f", (RedColor * 255))
        let RoundedGreen = String(format: "%0.0f", (GreenColor * 255))
        let RoundedBlue = String(format: "%0.0f", (BlueColor * 255))

        RedLabel.text = "Red: \(RoundedRed)"
        GreenLabel.text = "Green: \(RoundedGreen)"
        BlueLabel.text = "Blue: \(RoundedBlue)"


    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return colorName.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
        cell.textLabel?.text = colorName[indexPath.row]
                let str = colorName[indexPath.row]
                let array = str.components(separatedBy: ",")

                let num0 = CGFloat((array[0] as NSString).floatValue)
                let num1 = CGFloat((array[1] as NSString).floatValue)
                let num2 = CGFloat((array[2] as NSString).floatValue)
        print("Numbers \(num0) \(num1) \(num2)")
        cell.textLabel?.backgroundColor = UIColor(red: num0, green: num1, blue: num2, alpha: 1)


        return cell
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == UITableViewCell.EditingStyle.delete) {
            // handle delete (by removing the data from your array and updating the tableview)
            print("DELETED")
            self.colorName.remove(at: indexPath.row)
            self.tableView.beginUpdates()
            self.tableView.deleteRows(at: [indexPath], with: .middle)
            self.tableView.endUpdates()
            self.tableView.reloadData()
        }

    }
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let addNewButton = UITableViewRowAction(style: .destructive, title: "Add New", handler: { action, indexPath in
            print("addNewButton Clicked")
            print("addNewButton")
            self.tableView.beginUpdates()
            tableView.insertRows(at: [indexPath], with: .automatic)
            self.colorName.append("255,255,255")
            self.saveToPhone()
            tableView.reloadData()
            self.tableView.endUpdates()

        })
        let deleteButton = UITableViewRowAction(style: .destructive, title: "Delete", handler: { action, indexPath in
            print("Delete Clicked")
            if(self.colorName.count > 4){
            self.colorName.remove(at: indexPath.row)
            self.tableView.beginUpdates()
            self.tableView.deleteRows(at: [indexPath], with: .middle)
                self.saveToPhone()
                self.tableView.endUpdates()
            }else{
                print("YOU CANNOT DELETE MORE")
            }
        })
        deleteButton.backgroundColor = UIColor.red
        addNewButton.backgroundColor = UIColor.green

        return[deleteButton, addNewButton]
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
        let RoundedRed = String(format: "%0.0f", (RedColor * 255))
        let RoundedGreen = String(format: "%0.0f", (GreenColor * 255))
        let RoundedBlue = String(format: "%0.0f", (BlueColor * 255))
        var zeroRed = ""
        var zeroBlue = ""
        var zeroGreen = ""
        if(RoundedRed.count == 1){
            zeroRed = "00"
        }else if(RoundedRed.count == 2){
            zeroRed = "0"
        }else{
            zeroRed = ""
        }
        if(RoundedBlue.count == 1){
            zeroBlue = "00"
        }else if(RoundedBlue.count == 2){
            zeroBlue = "0"
        }else{
            zeroBlue = ""
        }
        if(RoundedGreen.count == 1){
            zeroGreen = "00"
        }else if(RoundedGreen.count == 2){
            zeroGreen = "0"
        }else{
            zeroGreen = ""
        }
        cell.textLabel?.text = "\(zeroRed)\(RoundedRed),\(zeroGreen)\(RoundedGreen),\(zeroBlue)\(RoundedBlue)"
        colorName[indexPath.row] = "\(zeroRed)\(RoundedRed),\(zeroGreen)\(RoundedGreen),\(zeroBlue)\(RoundedBlue)"
        saveToPhone()
        self.tableView.reloadData()
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    func saveToPhone(){
        let colorNameDefault = UserDefaults.standard
        colorNameDefault.setValue(self.colorName, forKey: "ColorNames")
        colorNameDefault.synchronize()
    }
}

enter image description here

enter image description here

1 answer

  • answered 2018-11-08 00:34 Harshal

    • clear the color of your text label at all times
      eg: cell.textLabel?.backgroundColor = UIColor.clear();

    • and Try setting the background color of your cell content view to what you want
      eg: cell.contentView?.backgroundColor = UIColor(red: num0, green: num1, blue: num2, alpha: 1);