【发布时间】:2016-12-25 06:59:40
【问题描述】:
我有一个应用程序需要在集合视图中自动滚动
class resultsViewController: UIViewController , UICollectionViewDataSource , UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
var numberCount = 3
var scrollIndex = 1
override func viewDidLoad() {
super.viewDidLoad()
let flow = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
flow.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
let width = UIScreen.mainScreen().bounds.size.width - 6
flow.itemSize = CGSizeMake(width/3, width/3)
flow.minimumInteritemSpacing = 3
flow.minimumLineSpacing = 3
flow.sectionInset = UIEdgeInsetsMake(0.0, 0.0,10,0);
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.doAfterThreeSecods()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageSearch", forIndexPath: indexPath) as! imagesCollectionViewCell
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberCount
}
func doAfterThreeSecods()
{
numberCount += 3
collectionView.reloadData()
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.doAfterThreeSecods()
}
}
}
每三秒添加 3 个单元格
当我附加三个单元格时,我只需要滚动下一行
self.collectionView.layoutIfNeeded()
self.collectionView.scrollToItemAtIndexPath(NSIndexPath(index: self.scrollIndex), atScrollPosition: UICollectionViewScrollPosition.Bottom, animated: true)
但应用程序崩溃并且错误是:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“尝试滚动到无效的索引路径:{length = 1, path = 6}”
任何人都可以提供帮助
【问题讨论】:
-
doAfterThreeSecods 在每 3sec 之后调用它自己。并且因为 collectionView.reloadData() 在这里被调用,所以它也是每 3 秒后调用一次。
-
scrollIndex 在 doAfterThreeSecond 调用中未增加
-
在单元格追加或单元格数计算错误之前滚动,6个单元格为0->5