Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is scrollViewWillEndDragging affecting a UICollectionView and UITableView?

I'm using an UITableView and a UICollectionView on the same View Controller.

I wanted to change how the UICollectionView scrolls, so I added a scrollViewWillBeginDragging and a scrollViewWillEndDragging function inside the extension.

However, scrollViewWillBeginDragging and a scrollViewWillEndDragging is also affecting the UITableView, despite not being in the same extension.

How do I fix this? Is there a way to only select the UICollectionView?

Here is a short version of what my code looks like:

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    // This is where I put all of the UICollectionView code, including `scrollViewWillBeginDragging` and a `scrollViewWillEndDragging`

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        // Why is the code in here affecting the UITableView?

    }

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        // Same as with `scrollViewWillBeginDragging`

    }

}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    // This is where I put all of the UITableView code, it's separate from the UICollectionView so why are `scrollViewWillBeginDragging` and `scrollViewWillEndDragging` affecting it?

}

like image 842
Richard Reis Avatar asked Sep 10 '25 14:09

Richard Reis


1 Answers

This is happening because

UITableViewDelegate and UICollectionViewDelegate both Inherits From UIScrollViewDelegate

So what you can do is

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    // This is where I put all of the UICollectionView code, including `scrollViewWillBeginDragging` and a `scrollViewWillEndDragging`

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

        if scrollView is UICollectionView {
          // Add code here for collectionView
        }
    }

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

        if scrollView is UICollectionView {
          // Add code here for collectionView
        }
    }

}
like image 89
Razi Tiwana Avatar answered Sep 12 '25 02:09

Razi Tiwana