2016-08-18 213 views
0

我有一个应用程序,它需要进行滚动集合视图中自动UICollectionView垂直自动滚动每3秒

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”,理由是:“试图滚动到无效的索引路径:{长度= 1,路径= 6}”

任何人都可以帮助

+0

doAfterThreeSecods呼吁它的每3秒后的自我。并且因为collectionView.reloadData()在这里被调用,所以它在每个3secs之后也被调用。 – Sofeda

+0

scrollIndex在doAfterThreeSecond中不递增调用 –

+0

在单元格追加之前滚动或计算出的单元格号错误,其6个单元格的0-> 5 – Tj3n

回答

0

你这样做以错误的方式。这就是为什么它会抛出无效的索引路径错误。例如,假设你有3个集合视图来显示。我们将其命名为image01,image02,image03。所以你的数组应该像[image03,image01,image02,image03,image01]。您应该将最后一个元素追加到第一个元素和最后一个元素。答案的描述非常广泛。因此这里是描述这个理论的文章。

Article :- 

https://adoptioncurve.net/archives/2013/07/building-a-circular-gallery-with-a-uicollectionview/