【问题标题】:Why is scrollViewWillEndDragging affecting a UICollectionView and UITableView?为什么 scrollViewWillEndDragging 会影响 UICollectionView 和 UITableView?
【发布时间】:2019-04-09 20:09:17
【问题描述】:

我在同一个视图控制器上使用 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?

}

【问题讨论】:

  • 您可以在委托函数中查看scrollView的superview。例如:if let view = scrollview.superView, view == collectionView {} 类似这样的东西。

标签: ios swift uitableview uicollectionview


【解决方案1】:

这是因为

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。现在它完全有道理。谢谢!
猜你喜欢
  • 2013-05-19
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 2011-03-06
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多