Detecting UIScrollView page change

2019-01-16 12:16发布

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

8条回答
2楼-- · 2019-01-16 12:45

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
           }
       }
   }
查看更多
萌系小妹纸
3楼-- · 2019-01-16 12:48

For Swift

static var previousPage: Int = 0
func scrollViewDidScroll(_ scrollView: UIScrollView){
let pageWidth: CGFloat = scrollView.frame.width
let fractionalPage: CGFloat = scrollView.contentOffset.x / pageWidth
let page = lround(Double(fractionalPage))
if page != previousPage
{
  print(page)
  // page changed
}
}
查看更多
登录 后发表回答