当视图像幻灯片一样显示时,自动滚动 UICollectionView 元素。

Scroll the UICollectionView elements automatically as the view appears like a slideshow.

我正在 swift 3 中处理一个项目,目前我可以通过一个接一个地拖动来浏览 UICollectionView 项目。我的要求是将它们(项目)显示为幻灯片,而不是在屏幕出现时拖动它们(需要禁用它)。到目前为止,我的代码如下。由于我是 swift 的新手,我们将不胜感激。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SuggestedCell", for: indexPath) as! SuggestedMP3CollectionViewCell
        //background of collectionview
        let view=UIView()
        view.backgroundColor=UIColor(patternImage:collectionViewImageArray [indexPath.row])
        cell.backgroundView=view
        cell.featuredSongLabel.text = "Featured Song"
        cell.suggestedHealerNameLabel.text = "Healer"
        cell.suggestedTeaserDescriptionLabel.text = "Teaser"
        cell.suggestedMusicImageView.image = imageArray [indexPath.row]
       // cell.suggestedMusicImageView.image = collectionViewImageArray [indexPath.row]
        return cell


    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

            return 20

       //return collectionViewCount!
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {

            return 1
    }

配置集合视图或重新加载它的那一刻,您需要为自动滚动添加一个计时器。

let kAutoScrollDuration: CGFloat = 4.0
var timer = Timer.scheduledTimer(timeInterval: kAutoScrollDuration, target: self, selector: #selector(self.nextPage), userInfo: nil, repeats: true)
RunLoop.main.addTimer(timer, forMode: NSRunLoopCommonModes)

现在您的计时器将在指定的时间间隔后调用 nextPage

func nextPage() {
        // 1.back to the middle of sections
    var currentIndexPathReset = self.resetIndexPath()
        // 2.next position
    var nextItem: Int = currentIndexPathReset.item + 1
    if nextItem == self.banners.count {
        nextItem = 0
    }
    var nextIndexPath = IndexPath(item: nextItem, section: 0)
    // 3.scroll to next position
    self.collectionView?.scrollToItem(at: nextIndexPath, atScrollPosition: .left, animated: true)
}

现在,如果我们已经到达最后一个索引,那么我们需要重置 indexPath,因此我们有 resetIndexPath 方法,它也会 return currentIndexPath。

func resetIndexPath() -> IndexPath {
        // currentIndexPath
    var currentIndexPath: IndexPath? = self.collectionView?.indexPathsForVisibleItems?.last
        // back to the middle of sections
    var currentIndexPathReset = IndexPath(item: currentIndexPath?.item, section: 0)
    self.collectionView?.scrollToItem(at: currentIndexPathReset, atScrollPosition: .left, animated: false)
    return currentIndexPathReset!
}