Group Group Group Group Group Group Group Group Group

Accessing cell content outside the cellForRowAt function

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

I have set up a custom function to effect this change. My problem is I have been unsuccessful in trying to access the cell properties of the cellForRowAt function from my custom function. I kept trying but kept getting no updates on the labels.

Please help.

My codes are as follows :

TableViewCellController :

class TableViewCellController: UITableViewCell {

@IBOutlet var index_BG: UILabel!
@IBOutlet var date_BG : UILabel!
@IBOutlet var time_BG: UILabel!
@IBOutlet var type_BG: UILabel!
@IBOutlet var notes_BG: UILabel!
@IBOutlet var read_BG: UILabel!

BGTest008VC(view controller) : 

  @IBOutlet var tableView008 : UITableView!

  var BGTest008: [BGTest008Class] = []



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

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

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

   
Background_Color()

return cell
}

func Background_Color(){

 let indexPath = indexPath_X
    let cell = tableView008.dequeueReusableCell(withIdentifier: "BGTest008", for:indexPath) as! TableViewCellController
    let type_BG = BGTest008[indexPath.row].type_BG
    if cell.type_BG.text == "Fasting"{
    cell.type_BG.backgroundColor = UIColor.yellow
  }

}
Thank you.

@vkvkcy Thanks very much for your question!

I believe the problem is here:

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

TableViewCellController is the name of the ViewController, and instead should be either UITableViewCell or the name of the subclass of the customer UITableViewCell.

I hope this helps!

All the best.

Hi thank you so much for your response.

I am a little confuse here - TableViewCellController is also the name of the TableViewCell class ( which is the subclass of the UITableViewCell - is it?)

I try using UITableViewCell but the app could not detect all the labels.

Maybe you could elaborate a little . Thank you so much.

@vkvkcy I believe you should first change the name of the subclass of UITableViewCell to something unique, like MyTableViewCell. This way, there is no confusion, or conflicts, and you can focus on isolating your outstanding issues.

Hi there,

I have change the name of the subclass to VKTestTableViewCell and then make subsequent changes at the cellForRowAt function and the Background_Color function. But still the labels are not updated.

Have attached the full quotes here hoping it would help. Thank you so much.

//
// ViewController.swift
// BGTest008
//
// Created by Vincent Koh on 1/4/20.
// Copyright © 2020 Vincent Koh. All rights reserved.
//

//------------------------------BGTest009_A----------------------------------------------

import UIKit
import CoreData

class BGTest008VC: UIViewController, UITableViewDelegate,UITableViewDataSource, NSFetchedResultsControllerDelegate {

@IBOutlet var tableView008 : UITableView!

var BGTest008: [BGTest008Class] = []

// var cell_1 : UITableViewCell

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"
self.indexPath_X = indexPath

   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 {
                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
let type_BG = BGTest008[indexPath.row].type_BG
if cell.type_BG.text == “Fasting”{
cell.type_BG.backgroundColor = UIColor.yellow// label has no update
}
}

func tableView(_ _tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

let deleteAction = UIContextualAction(style: .destructive, title:"Delete") {(action, sourceView, completionHandler) in
    // delete the row from the data store
    
    if let appDelegate = (UIApplication.shared.delegate as? AppDelegate){
        
        let context = appDelegate.persistentContainer.viewContext
        let dataToDelete = self.fetchResultController.object(at: indexPath)
            context.delete(dataToDelete)
        
        appDelegate.saveContext()
    }
    
    completionHandler(true)
}
    let swipeConfiguration = UISwipeActionsConfiguration(actions: [deleteAction])
    
    return swipeConfiguration

}

func controllerWillChangeContent(_ controller: NSFetchedResultsController){
tableView008.beginUpdates()

}

func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?){
//
switch type {
case .insert:
if let newIndexPath = newIndexPath {
tableView008.insertRows(at: [newIndexPath], with: .fade)

    }
case .delete:
    if let indexPath = indexPath {
        tableView008.deleteRows(at: [indexPath], with: .fade)

    }
case .update:
    if let indexPath = indexPath {
        tableView008.reloadRows(at: [indexPath], with: .fade)

}

default:
    tableView008.reloadData()

}

if let fetchedObjects = controller.fetchedObjects{
    BGTest008 = fetchedObjects as! [BGTest008Class]
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController) {
tableView008.endUpdates()

}

}

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)
        }
    }
}

}

@vkvkcy Do you still have issues with this?

so so sorry for my late reply. Was down with the C Virus. But back on my feet now. Yes I am still trying to figure this out. Still could not get it. sigh… Going to rework on it since it has been some time. Hope I could find solution if not hope you guys can help. Thanks so much.