在ViewController上的CollectionViewCell中使用PageControl

时间:2017-05-29 11:54:21

标签: ios swift uicollectionview uicollectionviewcell uipagecontrol

我试图在CollectionViewCell中显示图像的PageControl。

一切似乎都正常工作 - 页面数量是正确的,甚至print(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!

}

1 个答案:

答案 0 :(得分:0)

不确定它是否是最佳实践方式,但我将pageControl连接到我的EncounterDetailViewController而不是单元格中。

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
}
}