如何检测 UIPageViewController 的视图何时发生更改



我有一个带有PageViewController的应用程序,我想制作自己的自定义PageViewController指示器。一切都已准备就绪。我现在唯一需要做的就是弄清楚如何判断视图控制器的视图何时更改以及它当前在哪个视图上。

我已经链接到这个演示。在第一部分中,我单击顶部的按钮以更改页面和指示当前页面正在工作的滑块,但是之后我滑动手指以更改控制器,并且我想使滑块指示器随页面移动。

在这里,

我评论了如何使用PageViewController获取当前页面索引

func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool)
    {
        if (completed)
        {
            //No need as we had Already managed This action in other Delegate
        }
        else
        {
            ///Update Current Index
            Manager.pageindex = Manager.lastIndex
            ///Post notification to hide the draggable Menu
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateLabelValue"), object: nil)
        }
    }
    //MARK: Check Transition State
    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController])
    {
        ///Update Last Index
        Manager.lastIndex = Manager.pageindex
        ///Update Index
        Manager.pageindex = pages.index(of: pendingViewControllers[0])!
        ///Post notification to hide the draggable Menu
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateLabelValue"), object: nil)
    }

我已使用通知观察器通知主控制器有关页面更改和执行某些操作的信息

管理器是我的结构体,保存当前页码,你可以在结构体或类中随心所欲地保存索引

我的结构类

//Struct Class
struct Manager
{
    ///Current Page Index
    static var pageindex :Int = 0
    ///Last Index
    static var lastIndex :Int = 0
}

主要用途

switch Manager.pageindex
        {
        case 0:
            self.mainHomeLabel.text = "VC1"
        case 1:
            self.mainHomeLabel.text = "VC2"
        case 2:
            self.mainHomeLabel.text = "VC3"
        default:
            self.mainHomeLabel.text = "VC1"
        }

注意 相应代码中的任何查询请询问

更新 - 添加了演示项目链接

链接 - https://github.com/RockinGarg/PageViewController-Demo.git

如果你有一个要显示的页面数组,那么你可以使用UIPageViewControllerDelegate来检测页面更改。更具体地说,此功能 https://developer.apple.com/documentation/uikit/uipageviewcontrollerdelegate/1614091-pageviewcontroller 因为它会告诉您将要转换到什么。然后,您可以根据即将显示的视图控制器确定您所在的页面。

最新更新