【发布时间】:2017-01-07 13:06:11
【问题描述】:
我在UITableviewCell 中添加一个UICollectionView,然后添加此代码为我的UICollectionViewCell 设置动画:
let CardCollectionCellId = "CardCollectionCell"
let SlideShowTimeInterval = TimeInterval(7)
protocol CardCellDelegate {
func didSelectCard(card:Card)
}
class CardTableViewCell: UITableViewCell,UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
var category:CardCategory!
var delegate: CardCellDelegate!
var slideShow = true
@IBOutlet weak var overlayView: UIVisualEffectView!
@IBOutlet weak var collectionView:UICollectionView!
func configureCell(){
collectionView.register(UINib(nibName: "CardCollectionCell", bundle: nil), forCellWithReuseIdentifier: CardCollectionCellId)
initialzeTimerForCategory(category: category)
collectionView.reloadData()
}
// TODO:Ideally It should run when cell is visible
func initialzeTimerForCategory(category:CardCategory){
if category.isSlideShowOn && slideShow {
var rowIndex = 0
Timer.scheduledTimer(withTimeInterval: SlideShowTimeInterval, repeats: true) { (Timer) in
let items = self.collectionView.numberOfItems(inSection: 0)
if items > 0{
self.collectionView.scrollToItem(at: IndexPath(item: rowIndex, section: 0), at: UICollectionViewScrollPosition.centeredHorizontally, animated: false)
rowIndex = rowIndex < (items - 1) ? (rowIndex + 1) : 0
}
print("=========>",items,rowIndex)
}
}
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.category.cards.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let card = self.category.cards[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CardCollectionCellId, for: indexPath) as! CardCollectionCell
cell.configureCell(card: card)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.delegate.didSelectCard(card: self.category.cards[indexPath.row])
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIScreen.main.bounds.width
return CGSize(width: width - 20, height: 350)
}
}
当我不滚动表格时代码工作正常,但是当我滚动表格时它会崩溃并抛出此错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'attempt to scroll to invalid index path: <NSIndexPath: 0x600000231aa0> {length = 2, path = 0 - 1}'
提前致谢。
【问题讨论】:
-
我认为您遗漏了一些可以更容易发现问题的代码,您能否展示一下您是如何填充数据源的?
-
这个错误通常是因为它试图滚动到不存在的东西,所以 indexpath 不存在
-
@bolnad 更新了我的完整代码,我知道当我们尝试滚动查找不存在的索引路径时会出现此问题。
-
@dirtydanee,我已经探讨过这个问题,但该问题的解决方案对我没有帮助。