Page 462 showDatePicker()

The function in the book has us search for the date row with the indexpath to set the tint color on the cell’s detail text label. However, I am getting nil for that value. Since we have the date label as an outlet, why can’t the tint be set that way?

Hey Kurtbitner, I finished this tutorial a few days ago and thought I’d try it out.
I’m assuming you are referring to this code:

show func showDatePicker()
class ItemDetailViewController: UITableViewController {
...

  func showDatePicker() {
    datePickerVisible = true
    
    let indexPathDateRow = IndexPath(row: 1, section: 1)
    let indexPathDatePicker = IndexPath(row: 2, section: 1)

    if let dateCell = tableView.cellForRow(at: indexPathDateRow) {
      dateCell.detailTextLabel!.textColor = dateCell.detailTextLabel!.tintColor
    }
    
    tableView.beginUpdates()
    tableView.insertRows(at: [indexPathDatePicker], with: .fade)
    tableView.reloadRows(at: [indexPathDateRow], with: .none)
    tableView.endUpdates()
    
    // Passes users original date info into picker.
    datePicker.setDate(dueDate, animated: false)
  }

I tried what you suggested with success!

func showDatePicker() {
    datePickerVisible = true
    dueDateLabel.textColor = UIColor.red // Added this!
    
    let indexPathDateRow = IndexPath(row: 1, section: 1)
    let indexPathDatePicker = IndexPath(row: 2, section: 1)
    
    /* Removed this code
    if let dateCell = tableView.cellForRow(at: indexPathDateRow) {
      dateCell.detailTextLabel!.textColor = dateCell.detailTextLabel!.tintColor
    }*/

    // Rest of method is left unchanged

You are absolutely correct. Since we are using static table view cells and we have an outlet to the cell in question, you can directly modify the cell instead of getting a reference to the cell via cellForRow. So that approach would work just fine.

Do note though that this only works with static table views. If you have dynamic rows, you can not be certain that a table row is available at any given point unless it is in the visible range of rows. So, it’s safer to code defensively and check if a row is available in general cases.

Good catch here though - I will add an explanation about this to the next update so that this is made clearer.

For your specific code, if you want to figure out why cellForRow is returning nil for you, create a ZIP file of your project, upload it somewhere and provide a link and I’ll take a look.

This topic was automatically closed after 166 days. New replies are no longer allowed.