PageViewController index des pages en cours dans Swift

je veux obtenir l'index courant d'un pageeviewcontroller, Je ne sais pas comment j'obtiens l'index des pages visibles.

func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool,previousViewControllers: [UIViewController],transitionCompleted completed: Bool)
{
    // How to get it?

}
19
demandé sur IPS Brar 2015-09-28 15:17:27

7 réponses

vous pouvez utiliser didFinishAnimating, et définir des tags pour viewcontrollers. essayez ceci

func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
{
   if (!completed)
  {
    return
  }
  self.pageControl.currentPageIndex = pageViewController.viewControllers!.first!.view.tag //Page Index
}
21
répondu manukv 2015-09-28 12:38:23

Swift 3: plein programmatique PageViewController exemple pour obtenir/mise à l'index de la page sans afficher de marquage:

enum PageViewType:String {
        case green = "greenView"
        case blue = "blueView"
        case red = "redView"  
}

class MyPageViewController: UIPageViewController {

    private (set) lazy var orderedViewControllers:[UIViewController] = {
         return [self.newPageView(.green),
                self.newPageView(.blue),
                self.newPageView(.red)
        ]
    }

    var currentIndex:Int {
            get {
                return orderedViewControllers.index(of: self.viewControllers!.first!)!
            }

            set {
                guard newValue >= 0,
                    newValue < orderedViewControllers.count else {
                    return
                }

                let vc = orderedViewControllers[newValue]
                let direction:UIPageViewControllerNavigationDirection = newValue > currentIndex ? .forward : .reverse            
                self.setViewControllers([vc], direction: direction, animated: true, completion: nil) 
            }
        }

    override func viewDidLoad() {
        super.viewDidLoad()

        dataSource = self

        if let firstViewController = orderedViewControllers.first {
            setViewControllers([firstViewController],
                           direction: .forward,
                           animated: true,
                           completion: nil)
        }
    }

    private func newPageView(_ viewType:PageViewType) -> UIViewController {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: viewType.rawValue)       
        return vc
    }
}

UIPageViewController mise en œuvre de la source de données:

extension MyPageViewController:UIPageViewControllerDataSource {

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

        let previousIndex = currentIndex - 1

        guard previousIndex >= 0 else {
            return nil
        }

        guard orderedViewControllers.count > previousIndex else {
            return nil
        }

        return orderedViewControllers[previousIndex]   
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {         
        let nextIndex = currentIndex + 1

        guard orderedViewControllers.count != nextIndex else {
            return nil
        }

        guard orderedViewControllers.count > nextIndex else {
            return nil
        }

        return orderedViewControllers[nextIndex]
    }

    func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
        return orderedViewControllers.count
    }

    func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {

        return currentIndex
    }
}
8
répondu Peter Kreinz 2017-02-06 22:30:07

Dans Swift 3

Remplacer didFinishAnimating fonction de UIPageViewControllerDelegate comme ceci:

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    if completed {
        if let currentViewController = pageViewController.viewControllers![0] as? WalkthroughContentViewController {
            pageControl.currentPage = currentViewController.index
        }
    }
}

N'oubliez pas de garder une variable d'index à l'intérieur du WalkthroughContentViewController. En outre, dans le jeu de méthode viewDidLoad:

delegate = self
7
répondu George Bikas 2017-06-29 09:38:29

essayez..

func pageViewController(pageViewController: UIPageViewController,didFinishAnimating finished: Bool,previousViewControllers: [UIViewController],transitionCompleted completed: Bool){
guard completed else { return }

self.pageControl.currentPage = pageViewController.viewControllers!.first!.view.tag
    }
3
répondu Sankalap Yaduraj Singh 2015-09-28 12:49:50

N'oubliez pas de configurer le délégué de pageviewcontroller.

 func createPageViewController() {
    // Create page view controller
    pageViewController = storyboard?.instantiateViewController(withIdentifier: "PageViewController") as? UIPageViewController
    pageViewController?.delegate = self
    pageViewController?.dataSource = self

    let startingViewController: ChildViewController = viewControllerAtIndex(index: 0)!
    let viewControllers: Array = [startingViewController]
    pageViewController?.setViewControllers(viewControllers, direction: .forward, animated: true, completion: nil)

    self.addChildViewController(pageViewController!)
    self.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height)
    self.view.addSubview((pageViewController?.view)!)
    self.pageViewController?.didMove(toParentViewController: self)
}

func viewControllerAtIndex(index: Int) -> ChildViewController? {  
    // return nil here, if there won't be any page in pageviewcontroller

    // Create a new view controller and pass suitable data.
    let pageContentViewController: ChildViewController = storyboard?.instantiateViewController(withIdentifier: "ChildViewController") as! ChildViewController

    pageContentViewController.pageIndex = index
    return pageContentViewController
}

//Also add viewControllerAfter and viewControllerBefore methods

func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
    self.pendingIndex = (pendingViewControllers.first as! ChildViewController).pageIndex
}

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    if completed {
        self.currentIndex = self.pendingIndex!
        //Perform your task here
    }
}
0
répondu Rupak Shakya 2018-02-20 18:37:04

Vous pouvez utiliser la méthode suivante:

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    guard
        completed,
        let viewControllerIndex = tutorialViews.index(of: pageViewController.viewControllers!.first!) else
            return
        }

    self.currentIndex = viewControllerIndex
}

tutorialViews est un tableau de pages (ViewControllers).

Et initialiser currentIndex comme ça:

var currentIndex = 0 {
    didSet {
        self.updateContentForPage(withIndex: currentIndex)
    }
}
0
répondu Mykyta Savchuk 2018-03-26 10:29:20

Créer une méthode dans, par exemple, la classe -> WalkthroughPageViewController), tels que:

 /* 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)
    }
}

et dans la classe qui contrôle ledit UIPageController, qui sera une vue de contrôleur (class -> WalkthroughContentViewController) et qui contient un bouton Suivant qui passe à la page suivante et met à jour la propriété "pageControl.currentPage" (qui est lui-même UIpageControl), implémente:

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

}

0
répondu juan carlos merlos albarracin 2018-09-18 21:15:00