0

我試圖爲CollectionViewCell中的圖像顯示PageControl。在ViewController的CollectionViewCell中使用PageControl

一切似乎工作正常 - 頁數是正確的,甚至打印(currentPage)顯示正確的索引;但是,PageControl不顯示正確的當前頁面。

EncounterDetailViewController.swift

class EncounterDetailViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate { 

// MARK: - Properties 
var selectedEncounter: Encounter? 
var currentPage = 0 

// MARK: - UICollectionViewDataSource 
func numberOfSections(in collectionView: UICollectionView) -> Int { 
    return 1 
} 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return (selectedEncounter?.images.count)! 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath) as! EncounterCollectionViewCell 

    cell.imageView.sd_setImage(with: URL(string: (selectedEncounter?.images[indexPath.row])!)) 
    cell.pageControl.numberOfPages = (selectedEncounter?.images.count)! 
    cell.pageControl.currentPage = self.currentPage 

    return cell 
} 

// MARK: - ScrollView Delegate Method 
func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    let pageWidth = scrollView.frame.width 
    self.currentPage = Int((scrollView.contentOffset.x + pageWidth/2)/pageWidth) 
    print(currentPage) 
} 

} 

EncounterCollectionViewCell.swift

class EncounterCollectionViewCell: UICollectionViewCell { 

    // MARK: - Outlets 
    @IBOutlet weak var imageView: UIImageView! 
    @IBOutlet weak var pageControl: UIPageControl! 

} 
+0

哪一頁做了'pageControl'節目嗎? –

+0

你有一個'pageControl',但是你正在計算'currentPage'基於'collectionView'' contentOffset'。爲什麼? –

+0

我試圖改變基於每個水平滾動pageControls currentPage。 – pmanning

回答

0

不知道這是最好的實踐方式,但我連我的EncounterDetailViewController而不是細胞內的PageControl。

class EncounterDetailViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate { 

    @IBOutlet weak var pageControl: UIPageControl! 

    // MARK: - Properties 
    var currentPage = 0 

    // MARK: - View did load 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.pageControl.numberOfPages = (selectedEncounter?.images.count)! 

    } 

    // MARK: - ScrollView Delegate Method 
func scrollViewDidScroll(_ scrollView: UIScrollView) { 
    let pageWidth = scrollView.frame.width 
    self.currentPage = Int((scrollView.contentOffset.x + pageWidth/2)/pageWidth) 
    self.pageControl.currentPage = self.currentPage 
} 
} 
相關問題