为什么scrollViewWillEndDragging会影响到UICollectionView和UITableView?

3
我在同一个视图控制器上使用了UITableView和UICollectionView。
我想要更改UICollectionView的滚动方式,所以我在扩展中添加了scrollViewWillBeginDragging和scrollViewWillEndDragging函数。
然而,即使不在同一扩展中,scrollViewWillBeginDragging和scrollViewWillEndDragging也会影响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?

}


你可以在代理函数中检查scrollView的superview。例如:if let view = scrollview.superView, view == collectionView {} 就像这样。 - Coder ACJHP
1个回答

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

}

我不知道UITableViewDelegate也继承自UIScrollViewDelegate。现在这一点变得非常清晰了。谢谢! - Richard Reis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接