UIPageViewController。如何设置自定义UIViewControllers数组

时间:2019-05-28 20:26:39

标签: ios swift xcode uipageviewcontroller

我有一组4个UIViewController,都有各自的自定义类,并且设置了委托。到目前为止,我在主视图中有容器视图,这些视图在屏幕外滚动,这就是我在做“伪页面视图控制器”的方式。但是,为了进行培训,我想使用UIPageViewController将其转换为实际的页面视图控制器。
我看过很多教程,但是大多数人只使用一个视图控制器并更改其中的文本以显示多个视图控制器。就我而言,我有4个自定义视图控制器:

var glanceController: GlanceVC!
var goalsController: GoalsVC!
var commuteController: CommuteVC!
var compareController: CompareVC!

在我以前的伪页面视图控制器上,我像这样对它们进行初始化:

func loadVC() {
    glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC
    goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC
    commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC
    compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC
}

现在,据我了解,UIPageViewController需要一个UIViewControllers数组。但是我无法创建此数组:

var VCArray: [UIViewController] = [glanceController, goalsController, commuteController, compareController]

错误:无法在属性初始化程序中使用实例成员'glancecontrolleer'。

我尝试改为声明一个空数组var VCArray:[UIViewcontroller] = [] 然后在

之后添加
func loadVC() {
    glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC
    goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC
    commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC
    compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC
    VCArray += glanceController
}

但是也有一个错误:“参数类型@value glanceVC?与预期的类型“序列”不符。

有人可以帮我为uipageview制作此系列的自定义视图控制器吗?

1 个答案:

答案 0 :(得分:1)

创建一个计算属性并返回视图控制器数组

var VCArray: [UIViewController] {
    if let glanceController = self.storyboard?.instantiateViewController(withIdentifier: "sbGlance") as? GlanceVC,
        let goalsController = self.storyboard?.instantiateViewController(withIdentifier: "sbGoals") as? GoalsVC,
        let commuteController = self.storyboard?.instantiateViewController(withIdentifier: "sbCommute") as? CommuteVC,
        let compareController = self.storyboard?.instantiateViewController(withIdentifier: "sbCompare") as? CompareVC {
            return [glanceController, goalsController, commuteController, compareController]
    }
    return []
}