title: Accessing UITableView Header View
body: <p>I have a UITableView where the section header view contains a UITextField that the user can key in values. When I want to save the value that user keyed in, I need to access the table section header.</p>
  
  <p>I tried using the method <code>headerView(forSection:)</code>, and I put <code>headerView(forSection: 0)!</code> as a test to make sure that the section header definitely exists, but every time when I run the programme, the line where the method is returns an error "unexpectedly found <code>nil</code> while unwrapping an optional value".</p>
  
  <p>I have also tried to tag the UITextField, but when I attempt to access the section header using <code>certainTableView.viewWithTag(_ tag:)</code>, and cast the resulting UIView to UITextField, there is an error thrown at the line where casting happens, saying "Could not cast value of type 'UITableView' to 'UITextField'."</p>
  
  <p>Both errors look pretty bizarre to me. In the first case, I made sure that the section header is existent, yet the method returned <code>nil</code>. In the second case, the returned tagged view should be of type UITableViewHeaderFooterView, yet the type is UITableView. Can someone suggest any possible reason why this is so and how to correct?</p>
  
  <p>Or alternatively, is there any better approach to access the section header view so that I can save the text keyed in in the UITextField?</p>
  
  <p>Below is the detail that I used in the first case.</p>
  
  <p>In <code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -&gt; UIView?</code>, I returned a UIView that contains a UITextField. In the table view which I need to save the keyed-in user data, I have a button that, when the user taps it, data are saved. Within that selector, I have the following:</p>
  
  <pre><code>//save item
      let a = addItemTableView.headerView(forSection: 0)!
      let b = a.subviews[0] as! UITextField
      let c = b.text ?? ""
      someNSManagedObject.text = c
  </code></pre>
  
  <p>The error I mentioned above appears at the first line.</p>