我正在快速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
}
最佳答案
一旦配置了集合视图或重新加载它,就需要添加一个自动滚动计时器。
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!
}
关于ios - 当 View 看起来像幻灯片一样时,自动滚动UICollectionView元素。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42618577/