Cell, Tableview

I am trying to change the background color of certain UILabels based on the value of one of the labels.

I have 6 labels and if the value of one of the labels ie. type_BG is “Fasting” then the background of all other labels will become yellow.

To do this I constructed a custom function called “Background_Color.” It is here where the codes to changing the background color of the labels takes place. Something like :

if cell.type_BG.text == “Fasting”{
cell.type_BG.backgroundColor = UIColor.yellow
cell.read_BG.backgroundColor = UIColor.yellow
cell.read_index.backgroundColor = UIColor.yellow

				…. and so on.
}

When I run the codes, nothing happen. I believe the way I reference the cell pointing to the label is wrong. If so how should I correct it?

Thank you in advance.

My codes :

import UIKit
import CoreData

class BGTest008VC: UIViewController, UITableViewDelegate,UITableViewDataSource, NSFetchedResultsControllerDelegate {

@IBOutlet var tableView008 : UITableView!

var BGTest008: [BGTest008Class] = []

var TV_cell = VKTestTableViewCell()

@IBOutlet var BGtest008VC : UITableView!

var fetchResultController: NSFetchedResultsController<BGTest008Class>!

var recordCount1 : Int = 0
var x : String = ""
var indexPath_X : IndexPath = IndexPath.init(row: 0, section: 0)

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
     DispatchQueue.main.async {
          //  self.tableView.reloadData()
        self.tableView008.reloadData()
        }
    }


override func viewDidLoad() {
    
    print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))
    
    super.viewDidLoad()
    
    
        // 2) Declare an instance variable for fetch result controller
                                      let fetchRequest: NSFetchRequest<BGTest008Class> = BGTest008Class.fetchRequest()
                              
                              // 3) Deploy Standdard codes
                                      let sortDescriptor = NSSortDescriptor(key: "index_BG", ascending: true)
                                      fetchRequest.sortDescriptors = [sortDescriptor]
                              
                              if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
                                  let context = appDelegate.persistentContainer.viewContext
                                  
                                  //Initialize the fetchResultController
                                  fetchResultController = NSFetchedResultsController(
                                          fetchRequest: fetchRequest,
                                          managedObjectContext: context,
                                          sectionNameKeyPath:nil, cacheName: nil)
                                  fetchResultController.delegate = self
                                  
                                  do{
                                      try fetchResultController.performFetch()
                                      if let fetchedObjects = fetchResultController.fetchedObjects{
                                            BGTest008 = fetchedObjects
                                          
                                      }
                                  } catch {
                                      print(error)
                                  }
                              }
    
            
           self.tableView008.delegate = self
           self.tableView008.dataSource = self
    
}

func numberOfSections(in tableView: UITableView) -> Int {
return 1

  }

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cellIdentifier = "BGTest008"

let cell = tableView008.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! VKTestTableViewCell

    if let date_vk = BGTest008[indexPath.row].date_BG{
                
                let date_Format = DateFormatter()
                    date_Format.dateFormat = "yyy-mm-dd hh:mm a"
                let date_Format_Print = DateFormatter()
                    date_Format_Print.dateFormat = "EEE, dd-MMM"
                let date_label = date_Format_Print.string(from: date_vk)
                
                    cell.date_BG.text = date_label
                }
            
if let time_vk = BGTest008[indexPath.row].time_BG{
                
                let time_Format = DateFormatter()
                    time_Format.dateFormat = "yyy-mm-dd hh:mm a"
                    time_Format.timeZone = TimeZone(secondsFromGMT: 0)
                let time_to_str = time_Format.string(from: time_vk)
                let date_to_str = time_Format.date(from: time_to_str)
                    time_Format.dateFormat = "hh:mm:a"
                let time_back_to_string = time_Format.string(from: date_to_str!)
                let time_label = time_back_to_string
                
                    cell.time_BG.text = time_label
                }
        
let index_vk = BGTest008[indexPath.row].index_BG
                    cell.index_BG.text = "\(String(describing: index_vk))"
 
let BG_level = BGTest008[indexPath.row].read_BG
                    cell.read_BG.text = "\(String(describing: BG_level))"

let type_BG = BGTest008[indexPath.row].type_BG
        
            if let type_BG1 = type_BG{
                cell.type_BG.text = "\(String(describing: type_BG1))"

                if cell.type_BG.text == "Fasting"{
                    Background_Color()
            }else {
                    print("cell is not Fasting")
               // cell.type_BG.text = ""
                }
            }

return cell

}

func Background_Color(){
print("fasting 2")
let indexPath = indexPath_X
let cell = tableView008.dequeueReusableCell(withIdentifier: "BGTest008", for: indexPath) as! VKTestTableViewCell
cell.type_BG.backgroundColor = UIColor.yellow
cell.index_BG.backgroundColor = UIColor.yellow
cell.date_BG.backgroundColor = UIColor.yellow
cell.time_BG.backgroundColor = UIColor.yellow
cell.notes_BG.backgroundColor = UIColor.yellow
cell.read_BG.backgroundColor = UIColor.yellow
print("cell = Fasting")
}

func getRecordsCount() {
   let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "BGTest008")

    if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
        let context = appDelegate.persistentContainer.viewContext

   do {
       let recordCount = try context.count(for: fetchRequest)
                self.recordCount1 = recordCount
                print("recordCount = ", recordCount)
        } catch {
            print(error.localizedDescription)
        }
    }
}

}

Hello, why don't you modify the BackgroundColor in VKTestTableViewCell?
Just pass the model you wanna use to VKTestTableViewCell, and overwrite the model:
class VKTestTableViewCell : UITableViewCell {
var model : Model? {
didSet{
if self.model.type_BG == "Fasting" {
//Do something you wanna do here.
}
}
}
}
Also in call :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell = ...
cell.model = yourDataList[indexPath.row]
return cell
}

Hi there , thank tks for your response. The reason I am doing it this way its because I am curious to know how I can access the cell properties outside of the cellForRowAt function. Do you have any idea?

And also I think by creating a function for this (ie highlighting the labels) will make my code neater.

Thanks again and hoping to hear from you.

Hi so sorry for this very late reply. I was caught with many things many many difficult discruptions with the C virus. Anyway I have signed up so looking forward to participating more in this forum.

Cheers!