从scrollViewDidEndDecelerating访问collectionView

时间:2020-10-09 10:50:40

标签: ios swift uicollectionview uiscrollview

我有一个名为dayPicker的UICollectionView,它可以水平滚动,并允许您选择一个月中的某天。当用户停止滚动(scrollViewDidEndDecelerating)时,我希望该应用在这一天做些事情,可以从单元格的标签访问它。我在网上看到的所有答案都与此类似:https://stackoverflow.com/a/33178797/9036092

<form enctype="multipart/form-data" method="POST">
    …
</form> 

当我尝试从func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { var someCell : UICollectionViewCell = collectionView.visibleCells()[0]; // Other code follows... } 函数内部访问collectionView时,出现scrollViewDidEndDecelerating错误。当我替换UICollectionView的实际名称(dayPicker)时,它出现错误,提示“意外地找到nil,同时隐式展开了Optional值”。

我的问题是:如何从Ambiguous use of collectionView函数内部进入collectionView?目前,我的scrollViewDidSomething函数位于视图控制器的scrollViewDidEndDecelerating内部,并且我还尝试将其放在UICollectionViewDelegate扩展名中。

当前代码:

UIScrollViewDelegate

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

enter image description here

我还有另一种方法来确定用户在当天点击的时间,并且可以正常工作。尝试完成滚动结束的体验。

Xcode 11.4.1 / Swift 5

1 个答案:

答案 0 :(得分:0)

对于那些遇到此问题并寻找相同答案的人,我已经弄清楚了。非常感谢这里针对另一个问题的回答: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
    }
}
相关问题