0

I am working with a UIPageViewController and I have an array of viewcontrollers

lazy var subviewControllers: [UIViewController] = {
    return[
        UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController1") as! ViewController1,
        UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController2") as! ViewController2,
        UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController3") as! ViewController3
    ]
}()

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if let subview3 = subviewControllers[2] as? ViewController3 {
        subview3.customBar.alpha = 0.8 // <- error on this line
    }
}

But sometimes I have this error when I make a scroll:

Unexpectedly found nil while unwrapping an Optional value

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Fabio
  • 1,913
  • 5
  • 29
  • 53
  • Which line exactly is causing your error? – rmaddy Jul 31 '18 at 02:29
  • subview3.customBar.alpha = 0.8 – Fabio Jul 31 '18 at 02:30
  • You are accessing the view controller's outlets too soon. You should never directly access a view controller's outlets. Set a property and let the view controller update it's own outlets at the proper time. – rmaddy Jul 31 '18 at 02:31
  • Can you provide me an example please? This is my code @IBOutlet weak var customBar: customView! – Fabio Jul 31 '18 at 02:34
  • 1
    When reviewing the duplicate, look at [this answer](https://stackoverflow.com/a/49818897/1226963) since it closest addresses your issue and solution. – rmaddy Jul 31 '18 at 02:41
  • This example is just I needed, thanks – Fabio Jul 31 '18 at 02:49

0 Answers0