如何解决从scrollViewDidEndDecelerating访问collectionView
我有一个名为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的屏幕截图:
我还有另一种方法来确定用户在当天点击的时间,并且可以正常工作。尝试完成滚动结束的体验。
Xcode 11.4.1 / Swift 5
解决方法
对于那些遇到此问题并寻找相同答案的人,我已经弄清楚了。非常感谢这里针对另一个问题的回答: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
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。