【问题标题】:Access collectionView from scrollViewDidEndDecelerating从 scrollViewDidEndDecelerating 访问 collectionView
【发布时间】:2021-01-24 10:43:28
【问题描述】:

我有一个名为 dayPicker 的 UICollectionView,它可以水平滚动,让您选择月份中的哪一天。当用户停止滚动(scrollViewDidEndDecelerating)时,我希望应用程序在那天做一些事情,可以从单元格的标签访问。我在网上看到的所有答案都是这样的:https://stackoverflow.com/a/33178797/9036092

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    
    var someCell : UICollectionViewCell = collectionView.visibleCells()[0];
    
    // Other code follows...
}

当我尝试从scrollViewDidEndDecelerating 函数内部访问collectionView 时,我收到Ambiguous use of collectionView 错误。当我替换我的 UICollectionView (dayPicker) 的实际名称时,它会出现“在隐式展开可选值时意外发现 nil”的错误。

我的问题是:你如何从scrollViewDidSomething 函数内部到达collectionView?目前我的scrollViewDidEndDecelerating 函数在我的视图控制器中的UICollectionViewDelegate 中,我也尝试将它放在UIScrollViewDelegate 扩展中。

当前代码:

extension PageOneViewController: UICollectionViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let centerPoint = CGPoint(x: UIScreen.main.bounds.midX, y: scrollView.frame.midY)
        print(centerPoint) // Successfully prints the same center point every time scrolling stops
        let indexPath = collectionView.indexPathForItem(at: centerPoint) // Ambiguous error
        let indexPath = dayPicker.indexPathForItem(at: centerPoint) // Fatal error
    }
}

有问题的可滚动 UICollectionView 的屏幕截图:

我还有另一种方法可以让用户在当天点击,并且可以完美运行。尝试通过滚动结尾来完成体验。

Xcode 11.4.1/Swift 5

【问题讨论】:

  • 你试过self.collectionView吗?否则,可能会建议通过您设置的扩展程序中的变量来保持对collectionView 的强引用
  • 听起来您正在尝试访问超出范围的对象...使用断点单步执行您的代码并评估变量。如果您没有以这种方式发现错误,请尝试将minimal reproducible example 放在一起以获得更多帮助。
  • @SanzioAngeli 很棒的建议,不幸的是,我确实尝试过但没有成功。我也尝试在扩展中定义它,但 Xcode 告诉我我不能在扩展中定义变量?想出另一种方法,请参阅下面的答案。感谢您的帮助!

标签: ios swift uicollectionview uiscrollview


【解决方案1】:

我想通了,对于那些遇到此线程并寻找相同答案的人。非常感谢这里的另一个问题的答案:https://stackoverflow.com/a/45385718/9036092

缺少的部分是将scrollView 转换为UICollectionView,以便您可以访问collectionView 的单元格属性。

工作代码:

extension PageOneViewController: UICollectionViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let collectionView = scrollView as! UICollectionView // This is crucial
        
        let centerPoint = CGPoint(x: UIScreen.main.bounds.midX, y: scrollView.frame.midY)
        let indexPath = collectionView.indexPathForItem(at: centerPoint)
        let centerCell = collectionView.cellForItem(at: indexPath!) as! MyCustomCell
        let selectedDay = centerCell.dayLabel.text //
        print(selectedDay) // Prints the value of the day in the center of the collectionView, as a string
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    相关资源
    最近更新 更多