0

I'm lost on this one. I've read many answers to this particular question and I just can't get this working.

I have two view controllers - ScheduleService which is part of the storyboard and CalendarView which is not. I've got a calendar created in CalendarView and when a user selects a date on the calendar I'm wanting to push that date to label.text on ScheduleService.

At first I thought this would be easy:

let viewControllerSS = ScheduleService()
viewControllerSS.infoLabel.text = lbl.text

Intellisense sees the infoLabel control but when I try to assign a value to it I get the error stated in the title:

"Unexpectedly found nil while unwrapping an Optional values"

On the ScheduleService class I've got a label created:

@IBOutlet weak var infoLabel: UILabel!

How can I successfully push a value from lbl.text on CalendarView to infoLabel.text on ScheduleService without getting this error?

Will Buffington
  • 1,048
  • 11
  • 13
  • 2
    `ScheduleService()` creates a brand new instance of the controller whose outlets are not connected. This is **not** the instance in the storyboard. You need the reference to the storyboard instance with a segue or instantiation. – vadian Aug 28 '18 at 15:30
  • Okay, thank you for clearing that up. It'll have to be through instantiation as CalendarView is not on the storyboard (it's just a swift file in the project) so I can't use a segue, unless there's a way to create one programmatically. Would delegation solve this problem? – Will Buffington Aug 28 '18 at 15:37
  • because views are not loaded when you create an instance. One of the easiest ways to go around it is to force view so that it forces subviews to get created. let viewControllerSS = ScheduleService() _ = viewControllerSS.view viewControllerSS.infoLabel.text = lbl.text – James Kim Aug 29 '18 at 03:35

1 Answers1

0

With @IBOutlet you bind instances the storyboard instantiated for you. If you don’t instantiate from the storyboard, then the storyboard did not create them, nothing to bind to the variables so they stay nil.

You can instantiate your view controller through the storyboard, then init(coder:) will be called which sets up the binding, if you have done so in the storyboard.

If you rather want to do programmatic view controllers you have to create the label yourself, add it as subview and position it in viewDidLoad().

Fabian
  • 5,040
  • 2
  • 23
  • 35