How do I implement UIPageControl in Swift

后端 未结 4 1565
春和景丽
春和景丽 2021-02-02 10:30

Ok so I\'m struggling here and haven\'t been able to find a working solution. I\'ve been self learning Swift without Objective C experience (I know, I know).

In my app,

4条回答
  •  借酒劲吻你
    2021-02-02 10:55

    I think you and/or anyone else looking for how to do this will find this answer helpful. The code example enabled me to create a page control indicator on my scrollView, and it was the first time attempting to do this. I found it very clear.

    The lines you probably need to add to your project are:

    1: add UIScrollViewDelegate as a protocol when you first name your view controller class.

    2: in the class declaration create a pageControl variable. You will need to play with the frame numbers to get it to appear where you want it. the current numbers made one in the middle of the window for me. For reference the numbers mean (x position for top left corner of indicator, y coordinate for top left corner, width of page indicator, height of page indicator)

    var pageControl : UIPageControl = UIPageControl(frame: CGRectMake(50, 300, 200, 20))

    1. in viewDidLoad set the scrollView delegate and call `configurePageControl():

      override func viewDidLoad() {
          super.viewDidLoad()
      
          scrollView.delegate = self
      
          configurePageControl()
      }
      
    2. you need to add two methods after viewDidLoad. one is called in viewDidLoad

      func configurePageControl() {
           self.pageControl.numberOfPages = 
           self.pageControl.currentPage = 0
           self.pageControl.tintColor = UIColor.redColor()
           self.pageControl.pageIndicatorTintColor = UIColor.blackColor()
           self.pageControl.currentPageIndicatorTintColor = UIColor.greenColor()     
           self.view.addSubview(pageControl)
       }
      

      and

       func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
          let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
          pageControl.currentPage = Int(pageNumber)
      }
      

    The scrollView delegate is actually very simple to set up. Add UIScollViewDelegate as a protocol that your ViewController class will implement by adding it after the class declaration: class YourClassName: UIScrollViewDelegate. And then in viewDidLoad(), you complete the delegate setup by assigning the scroll view's delegate property to your class with the line scrollView.delegate = self. (again see the example I linked for if you need further clarification of where these commands go)

提交回复
热议问题