我在UICollectionView
中添加UITableviewCell
,然后添加此代码以动画我的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}'
提前致谢。
答案 0 :(得分:0)
查看您提供的代码后,看起来您尝试在UITableView上自动滚动集合视图。当您通过调用configureCell
中的cellForRowAtIndexPath
填充UITableView的单元格时,似乎会发生这种情况。
当您滚动浏览的每个单元格上调用cellForRowAtIndexPath
时,会发生什么样的情况,触发configureCell
。在configureCell
内,你可以配置一个Timer来重复动画。
我不知道你在哪里使该计时器无效,或者在完成该单元格后停止它。
你可以通过评论计时器并查看问题是否消失来测试这个理论。
如果出现此问题,那么解决此问题的最简单方法是实现UITableViewCell的prepareForReuse()
方法并使计时器无效。
这是Apple文档prepareForReuse