PageViewController current page index in Swift

前端 未结 12 2240
你的背包
你的背包 2021-02-01 15:37

I want to get current index of a pageViewController, I don\'t know how I get the visible pages index.

func pageViewController(pageViewController: UIPageViewContr         


        
12条回答
  •  無奈伤痛
    2021-02-01 16:11

    Create a method within, for example, class -> WalkthroughPageViewController), such that:

     /* The method takes in a page index and creates the next content view controller. If the controller can
     be created, we call the built-in setViewControllers method and navigate to the next view controller.*/
    func forward(index: Int) {
        if let nextViewController = contentViewController(at: index + 1) {
            setViewControllers([nextViewController], direction: .forward, animated: true, completion: nil)
        }
    }
    

    And in the class that controls said UIPageController, which will be a controller view (class -> WalkthroughContentViewController) and that contains a following button that passes to the next page and updates the property "pageControl.currentPage" (which is itself the UIpageControl), implements:

    class WalkthroughContentViewController: UIViewController {
    
    @IBOutlet var headingLabel: UILabel!
    @IBOutlet var contentLabel: UILabel!
    @IBOutlet var forwardButton: UIButton!
    @IBOutlet var pageControl: UIPageControl!
    @IBOutlet var contentImageView: UIImageView!
    
    var index     = 0
    var heading   = ""
    var content   = ""
    var imageFile = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        headingLabel.text = heading
        contentLabel.text = content
        contentImageView.image = UIImage(named: imageFile)
    
        // Update the 'currentPage' property of the page control.
        pageControl.currentPage = index
    
        if case 0...1 = index {
            forwardButton.setTitle("NEXT", for : .normal)
        } else if case 2 = index {
            forwardButton.setTitle("DONE", for : .normal)
        }
    }
    
    // MARK: - Actions
    
    @IBAction func nextButtonTapped(sender: UIButton) {
        switch index {
        case 0...1: /* Get the parent controller & call to the "forward" method from the 'WalkthroughPageViewController'. */
            let pageViewController = parent as! WalkthroughPageViewController
            pageViewController.forward(index: index)
        case 2: /* Dismiss the page view controller and show the main screen of the app*/
            dismiss(animated: true, completion: nil)
        default: break
        }
    }
    

    }

提交回复
热议问题