2016-08-18 83 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/