Martin Ma
Martin Ma

Reputation: 85

Swift: UIControl in TableViewController found nil when called by ViewController

I have two viewControllers in the storyboard, a ViewController (root) and a TableViewController, that are linked by a push segue.

The TableViewController acts as a setting page of the app and multiple UIControls such as UISegmentedControl and UISwitch are put in it. These UIControls are linked to the TableViewController via IBOutlets.

@IBOutlet weak var mySegmentedControl: UISegmentedControl!
@IBOutlet weak var mySwitch: UISwitch!

However, when I call these UIControls in the ViewController by:

let tableView: TableViewController = TableViewController.init(nibName: nil, bundle: nil)

if tableView.mySwitch.isOn {
//perform actions
}

Error pops up at the if-statment:

fatal error: unexpectedly found nil while unwrapping an Optional value

I thought it was because the TableViewController has not been loaded when the UIControls are being called, thus I have tried calling the viewDidLoad() of tableView first, but the error still remains.

What should I do? Appreciate any suggestions.

Upvotes: 0

Views: 81

Answers (1)

Andreas Oetjen
Andreas Oetjen

Reputation: 10209

You do not directly call viewDidLoad, this is done by UIKit after the view is being loaded. And the view is loaded when the view needs to be displayed.

If you need to access the outlets before, you can force loading by

tableView.loadViewIfNeeded()

But remember:

  • Maybe it's better to do the outlet stuff inside viewDidLoad of the involved controller, and not from outside.
  • You should not name the controller variable tableView. That name suggest to be a view and not a controller. Better name it tableViewCtrl or so.

Upvotes: 1

Related Questions