Get type of UIScrollView inside UIScrollViewDelegate methods

330 views Asked by At

I have a UIViewController that has UITableView and UICollectionView. I want to do certain tasks when UICollectionView is scrolled.

I've extended UIScrollViewDelegate and wrote my code in

func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView)

But this method is called when both UITableView and UICollectionView are scrolled. How do I differentiate between the two views here? I tried

  func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {

    if let cv = scrollView as? UICollectionView {

    }
  }

But it's not working. I tried po scrollView and the output is <uninitialized>.

2

There are 2 answers

0
Jawad Ali On

// Say tv and cv are outlets to table View and Collection View

Objective c

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tv) {
        self.tv.contentOffset = self.tv.contentOffset;
    } else if (scrollView == self.cv) {
        self.cv.contentOffset = self.cv.contentOffset;
    }
}

Swift

func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {

    if let scrollView == tv {
         //do whatever you need with tableView
    }
    if let scrollView == cv {
        //do whatever you need with collectionView
    }

  }
0
Sikander On

It was a mistake on my end but for others here I'll post the answer.

I needed to execute my code when slider has finished dragging/scrolling. To achieve that I had

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    NSObject.cancelPreviousPerformRequests(withTarget: self)
    perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation), with: nil, afterDelay: 0.3)
}

Problem was in line

perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation), with: nil, afterDelay: 0.3)

Instead of passing nil, I wrote

perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation), with: scrollView afterDelay: 0.3)

and that resolved it. I wasn't getting scrollView <uninitialized> anymore and my

if let cv = scrollView as? UICollectionView {

}

worked fine.