事件滚动(scrollViewDidScroll)从未调用 - Swift 3

时间:2016-12-15 23:08:14

标签: swift uiscrollview

我想检测用户滚动时,我使用了UIScrollView,我在ViewController中实现了UIScrollViewDelegate并尝试了scrollViewDidScroll,scrollViewDidEndScrollingAnimation以及所有其他活动,但这些事件从未被调用过。

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")
    }
}

1 个答案:

答案 0 :(得分:11)

您只需将委托添加到viewDidLoad() func:

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

 }