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

时间:2017-03-06 06:03:38

标签: ios swift swift3 uicollectionview uicollectionviewcell

我在swift 3中处理一个项目,目前我可以通过一个接一个地拖动来浏览UICollectionView项目。我的要求是在屏幕显示时将它们(项目)显示为幻灯片放映而不拖动它们(需要禁用它)。我现在的代码如下所示。因为我很快就会得到快速帮助,所以非常感谢。

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
    }

1 个答案:

答案 0 :(得分:2)

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

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方法,它也会返回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!
}