Detecting UIScrollView page change

前端 未结 10 2173
鱼传尺愫
鱼传尺愫 2020-12-07 17:11

Is there a way to detect or get a notification when user changes the page in a paging-enabled UIScrollView?

10条回答
  •  一生所求
    2020-12-07 17:53

    Swift 4

    I found the best way to do this is by using scrollViewWillEndDragging(_:withVelocity:targetContentOffset:). It lets you predict if paging will occur as soon as you lift your finger off the screen. This example is for paging horizontally.

    Remember to the assign the scrollView.delegate to the object that adopts UIScrollViewDelegate and implements this method.

    var previousPageXOffset: CGFloat = 0.0
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
    
        let targetOffset = targetContentOffset.pointee
    
        if targetOffset.x == previousPageXOffset {
            // page will not change
        } else if targetOffset.x < previousPageXOffset {
            // scroll view will page left
        } else if targetOffset.x > previousPageXOffset {
            // scroll view will page right
        }
    
        previousPageXOffset = targetOffset.x
        // If you want to track the index of the page you are on just just divide the previousPageXOffset by the scrollView width.
        // let index = Int(previousPageXOffset / scrollView.frame.width)
    
    
    }
    

提交回复
热议问题