Search code examples
swift3uipagecontrol

how to declare UIPageControl inside class


I'm trying to add pageControl to my collection View which is inside my collectionView Cell, so I need to declare UIPageControl so

let CollectionViewPageControl: UIPageControl = {
    let pageControl = UIPageControl()
    pageControl.frame = CGRect(x: 0, y: 100, width: 10, height: 10)
    pageControl.currentPage = 0
    pageControl.currentPageIndicatorTintColor = UIColor.red
    pageControl.pageIndicatorTintColor = UIColor.lightGray
    return pageControl
}

but I got this error Cannot convert value of type '() -> _' to specified type 'UIPageControl'

so any help ?


Solution

  • You're declaring collectionViewPageControl as an UIPageControl, but you're assigning a closure to it.

    You can do this:

    let collectionViewPageControl: UIPageControl = UIPageControl()
    collectionViewPageControl.frame = CGRect(x: 0, y: 100, width: 10, height: 10)
    collectionViewPageControl.currentPage = 0
    collectionViewPageControl.currentPageIndicatorTintColor = UIColor.red
    collectionViewPageControl.pageIndicatorTintColor = UIColor.lightGray
    

    You can read more about closures in Swift here.

    And don't forget to add it to your collectionViewCell (or whatever is the parent of the UICollectionView that will be paginated).

    yourCollectionViewCell.addSubview(collectionViewPageControl)