UICollectionView每隔3秒自动垂直滚动

时间:2016-08-18 11:07:25

标签: ios swift

我有一个应用需要自动在集合视图中滚动

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秒追加3个细胞

当我追加三个单元格时,我只需要滚动下一行

  self.collectionView.layoutIfNeeded()
        self.collectionView.scrollToItemAtIndexPath(NSIndexPath(index: self.scrollIndex), atScrollPosition: UICollectionViewScrollPosition.Bottom, animated: true)

但是应用程序崩溃,错误是:

由于未捕获的异常终止应用' NSInvalidArgumentException',原因:'尝试滚动到无效的索引路径:{length = 1,path = 6}'

任何人都可以提供帮助

1 个答案:

答案 0 :(得分:0)

你这样做是错误的。这就是它抛出无效索引路径错误的原因。例如,您需要显示3个集合视图。我们将其命名为image01,image02,image03。所以你的数组应该像[image03,image01,image02,image03,image01]。您应该将最后一个元素追加到第一个元素和第一个元素。答案的描述相当广泛。因此,这篇文章描述了这个理论。

 Article :- 
  

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