为什么scrollViewWillEndDragging会影响UICollectionView和UITableView?

Ric*_*eis 3 uitableview ios uicollectionview swift

我在同一个视图控制器上使用 UITableView 和 UICollectionView 。

我想更改 UICollectionView 的滚动方式,因此我在扩展中添加了一个scrollViewWillBeginDragging和 一个函数。scrollViewWillEndDragging

然而scrollViewWillBeginDragging ascrollViewWillEndDragging也是尽管不在同一个扩展中,但

我该如何解决?有没有办法只选择 UICollectionView?

这是我的代码的简短版本:

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?

}

Run Code Online (Sandbox Code Playgroud)

Raz*_*ana 6

发生这种情况是因为

UITableViewDelegate 和 UICollectionViewDelegate 都继承自 UIScrollViewDelegate

所以你能做的是

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
        }
    }

}
Run Code Online (Sandbox Code Playgroud)