PageViewController current page index in Swift

前端 未结 12 2264
你的背包
你的背包 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:20

    Use viewDidAppear that mark page as visible and viewDidDisappear that mark page as invisible

    Item ViewController:

    class PageItemViewController: UIViewController {
    
        private(set) var isVisible: Bool = false
    
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            isVisible = true
        }
    
        override func viewDidDisappear(_ animated: Bool) {
            super.viewDidDisappear(animated)
            isVisible = false
        }   
    }
    

    Get index of the visible page

    class PageViewController: UIPageViewController, UIPageViewControllerDelegate {
    
        var items: [PageItemViewController] = [] {
            didSet {
                if let last = items.last {
                    setViewControllers([last], direction: .forward, animated: true, completion: nil)
                }
            }
        }
    
        // ...
    
        public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
            if finished {
                guard let currentIndex = items.firstIndex(where: { $0.isVisible }) else { return }
                print(currentIndex)
            }
        }
    }
    

提交回复
热议问题