2017-03-06 116 views
1

我正在swift 3中處理項目,目前我可以通過拖動一個接一個地瀏覽UICollectionView項目。我的要求是在屏幕出現時將它們(項目)顯示爲幻燈片而不拖動它們(需要禁用該項目)。我現在的代碼如下圖所示。由於我對新的快速幫助將非常感激。當視圖像幻燈片一樣顯示時,自動滾動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 
    } 

回答

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) 

現在你的計時器將會在指定的時間間隔後,打電話下一頁現在

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! 
} 
+0

在「下一頁」功能,您可以解釋一下什麼是「self.banner.count」 – danutha

+1

對我來說self.banner.count給出的CollectionView細胞的數量,self.banner是對象 –

+0

的陣列十分感謝 – danutha