为什么scrollViewWillEndDragging影响UICollectionView和UITableView?

时间:2019-04-09 20:09:17

标签: ios swift uitableview uicollectionview

我在同一View Controller上使用UITableView和UICollectionView。

我想更改UICollectionView的滚动方式,因此在扩展程序中添加了scrollViewWillBeginDraggingscrollViewWillEndDragging函数。

但是,尽管scrollViewWillBeginDraggingscrollViewWillEndDragging不在同一扩展名中,但也影响了UITableView。

该如何解决?有没有办法只选择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?

}

1 个答案:

答案 0 :(得分:2)

这是因为

  

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

}