Detecting UIScrollView page change

前端 未结 10 2120
鱼传尺愫
鱼传尺愫 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 18:12

    Here is the swift solution for this.

    Make two properties currentPage and previousPage in the class where you are implementing your code and initialize them to 0.

    Now update currentPage from scrollViewDidEndDragging(:willDecelerate:) and scrollViewDidEndDecelerating(:scrollView:).

    And then update previousPage in scrollViewDidEndScrollingAnimation(_:scrollView:)

        //Class Properties
        var currentPage = 0
        var previousPage = 0
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
            updatePage(scrollView)
            return
        }
    
     func scrollViewDidEndDecelerating(scrollView: UIScrollView){
            updatePage(scrollView)
            return
        }
    
    
     func updatePage(scrollView: UIScrollView) {
            let pageWidth:CGFloat = scrollView.frame.width
            let current:CGFloat = floor((scrollView.contentOffset.x-pageWidth/2)/pageWidth)+1
            currentPage = Int(current)
    
            if currentPage == 0 {
                  // DO SOMETHING
            }
            else if currentPage == 1{
                  // DO SOMETHING
    
            }
        }
    
    func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
         if previousPage != currentPage {
              previousPage = currentPage
              if currentPage == 0 {
                  //DO SOMETHING
                 }else if currentPage == 1 {
                   // DO SOMETHING
               }
           }
       }
    

提交回复
热议问题