0

I try to keep a separate custom cell class, but somehow the datepicker I dragged into it from storyboard refuses to show up after I ran it.

import UIKit

class eventViewController: UIViewController,UITextViewDelegate,UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource  {
   @IBOutlet weak var timeTableView: UITableView!
   @IBOutlet weak var eventText: UITextView!
   @IBOutlet weak var scrollView: UIScrollView!

   override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view.
      self.eventText.delegate = self
      self.scrollView.delegate = self
      self.timeTableView.delegate = self
      self.timeTableView.dataSource = self
      self.timeTableView.register(startDateCell.self, forCellReuseIdentifier: "startDateCell")   
   }

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

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

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "startDateCell", for: indexPath) as! startDateCell
      //cell.startDatePicker.date = Date()
      //cell.text = "anything"
      return cell
   }
}

class startDateCell: UITableViewCell { 
   @IBOutlet weak var startDatePicker: UIDatePicker!
}

I have the outlet connected to my datePicker in the custom cell and I also defined my custom cell class to be startDateCell in inspector, and I registered my custom cell in my view controller. It will throw a runtime error saying the datepicker is nil.

Can somebody explain why it isn't showing up?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user3431800
  • 191
  • 2
  • 17

1 Answers1

0

Can you remove the following code from viewDidLoad() and ensure you have set reuse identifier of custom tableviewcell as "startDateCell" in storyboard and try again?

self.timeTableView.register(startDateCell.self, forCellReuseIdentifier: "startDateCell")

Anand
  • 1,820
  • 2
  • 18
  • 25
  • i figured it out myself but I would like to know why register cell will cause an error? And under what condition should I be using it? Free points and big thanks to you if you can clear that up. – user3431800 Jan 07 '18 at 07:00
  • register cell overrides the settings made in storyboard. As a result, datepicker outlet linked to custom cell in storyboard is ignored. Refer similar post here : https://stackoverflow.com/questions/24833391/simple-uitableview-in-swift-unexpectedly-found-nil/. And Quoting Paul Hudson from https://www.hackingwithswift.com/example-code/uikit/how-to-register-a-cell-for-uitableviewcell-reuse , "If you want to use register() with a Swift class, you provide a table view cell class as its first parameter. This is useful if your cell is defined entirely in code". Hope this helps :-) – Anand Jan 07 '18 at 07:09