如何解决使用 scrollViewDidScroll 处理多个 Collection View Cell
我目前正在使用 UICollectionView
为我的 scrollViewDidScroll
单元格的偏移设置动画。集合视图以前只包含 1 个 UICollectionViewCell
。
我刚刚在同一个集合视图中添加了另一个 UICollectionViewCell
,并且想要执行相同的动画。问题是,我因错误而崩溃:
Precondition Failed: NSArray element Failed to match the Swift Array Element type. Expected DetailedCell but found BasicCell
我的进步:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// First (Detailed Cell)
for newDetailedCell in mainCV.visibleCells as! [DetailedCell] { // Crashes on this line
let indexPath = mainCV.indexPath(for: newDetailedCell)
print("indexPath for Detailed Cell: \(indexPath)")
}
// Rest (Basic Cell)
for basic in mainCV.visibleCells as! [BasicCell] {
let indexPath = mainCV.indexPath(for: basic)
print("indexPath for Basic Cell: \(indexPath)")
}
}
如何使用两个不同的 CollectionViewCell 访问visibleCells?
解决方法
你可以试试
for cell in mainCV.visibleCells {
if let res = cell as? DetailedCell {
//
}
else
if let res = cell as? BasicCell {
//
}
}
或
let detailCells = mainCV.visibleCells.filter { $0 is DetailedCell }
for newDetailedCell in detailCells as! [DetailedCell] {
let indexPath = mainCV.indexPath(for: newDetailedCell)
print("indexPath for Detailed Cell: \(indexPath)")
}
,
要处理多个 UICollectionView
的滚动事件,请在 scrollViewDidScroll
内实现此条件:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == collectionView1 {
// Your code goes here
}
if scrollView == collectionView2 {
// Your code goes here
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。