Swift – Event scrolling (scrollViewDidScroll) never called – Swift 3

swiftuiscrollview

I would like to detect when the user scroll, I used a UIScrollView, I implemented the UIScrollViewDelegate in my ViewController and tried scrollViewDidScroll, scrollViewDidEndScrollingAnimation and all the others but these events are never called.

import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {     

    @IBOutlet weak var scrollView: UIScrollView!    

    override func viewDidLoad() {        
        super.viewDidLoad()    

        let xOrigin = self.view.frame.width

        let view1 = View1(frame: CGRect(x: 0, y: 0, width:self.view.frame.width, height: self.view.frame.height))
        let view2 = View2(frame: CGRect(x: xOrigin, y: 0, width: self.view.frame.width, height: self.view.frame.height))
        let view3 = View3(frame: CGRect(x: xOrigin * 2, y: 0, width: self.view.frame.width, height: self.view.frame.height))

        scrollView.addSubview(view1)
        scrollView.addSubview(view2)
        scrollView.addSubview(view3)

        self.scrollView.contentSize = CGSize(width: self.view.frame.width * 3, height: self.view.frame.height)

        // hide the scrol bar.
        scrollView?.showsHorizontalScrollIndicator = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("end scroll")
    }


    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        print("end scroll")
    }
}

Best Answer

You just have to add the delegate to your viewDidLoad() func:

override func viewDidLoad() {        
    super.viewDidLoad()  
    //add this line
    self.scrollView.delegate = self

 }
Related Topic