Search code examples
swiftxcodenulluiscrollview

Why is the scroll view being nil?


I have the following code:

extension SegmentedControlViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // this checks for whether contentOffset.x is around 10 (contented shifted to the right by 10 points)
        if abs(scrollView.contentOffset.x - 10) < 1 {
            print("works")
        }
    }
}
  @IBOutlet weak var scrollView: UIScrollView!

then I call the function in the viewDidLoad like this:

scrollViewDidScroll(scrollView)

Although I am always getting the error message

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

What am I doing wrong, how to Get the scroll view to not be nil.


Solution

  • Assign the scroll view's .delegate in viewDidLoad() and start scrolling:

    class SegmentedControlViewController: UIViewController {
    
        @IBOutlet weak var scrollView: UIScrollView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // assign the delegate      
            scrollView.delegate = self
            
        }
    
    }
    
    extension SegmentedControlViewController: UIScrollViewDelegate {
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            // this checks for whether contentOffset.x is around 10 (contented shifted to the right by 10 points)
            if abs(scrollView.contentOffset.x - 10) < 1 {
                print("works")
            }
        }
    }
    

    Edit

    If you want to check if the scroll view content has been dragged to the right more than 10 points, use this:

    extension SegmentedControlViewController: UIScrollViewDelegate {
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            // this checks for whether contentOffset.x is around 10 (contented shifted to the right by 10 points)
            if scrollView.contentOffset.x < 10 {
                print("scroll content has been dragged to the right more than 10 points")
            }
        }
    }