问题
I have a VC that contains a collectionView
and a scrollView
. I put this code to change current page of pageController
by scrolling in scrollView :
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
self.pageController.currentPage = Int(pageNumber)
}
It works nice for scrollView
but the problem is when i even scroll in collectionView
it declares and causes unwanted changing in pageController
!
What should i do?
回答1:
In addition to the answers posted above, You can make use of the tag property of the view.
Just assign a tag (Int) to your scrollview either in xib or via code.
yourScrollView.tag = 10
And in the scrollview delegate method check for this tag:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.tag == 10 {
///Your scrollview was scrolled
} else {
// Collection view was scrolled
}
}
回答2:
if scrollView == yourScrollView{
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
self.pageController.currentPage = Int(pageNumber)
}
check if the instance running the method is actually your scrollView
回答3:
First you have to understand bit detail about UICollectionView
. The UICollectionView
is subclassed from UIScrollView
. That's why its getting called for both the scrolling (Scrolling collection view and scrolling scroll view). You can do like this to differentiate what type of scrolling it is,
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == "Your scrollView outlet name" { // Scroll view
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
self.pageController.currentPage = Int(pageNumber)
} else {
// Collection view
}
}
Thanks.
回答4:
You need to check the scrollView
inside the scrollViewDidEndDecelerating
if it is your scroll view or your collection view.
Just add an if scrollView == myScrollView
before doing the 2 lines of code you have.
Your code shoudl look like this
func
scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == myScrollView {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
self.pageController.currentPage = Int(pageNumber)
}
}
来源:https://stackoverflow.com/questions/44455450/ios-scrollviewdidenddecelerating-runs-for-both-scrollview-and-collectionview