如何使用Swift为PageViewController中的所有UIViewController类设置相同的背景?

时间:2016-02-13 19:41:20

标签: ios swift uiviewcontroller

我正在创建PageViewController并遵循本教程:

https://spin.atomicobject.com/2015/12/23/swift-uipageviewcontroller-tutorial/

作者通过编写:

创建一个包含UIViewControllers的数组
private(set) lazy var orderedViewControllers: [UIViewController] = {
    return [self.newColoredViewController("Green"),
        self.newColoredViewController("Red"),
        self.newColoredViewController("Blue")]
}()

private func newColoredViewController(color: String) -> UIViewController {
    return UIStoryboard(name: "Main", bundle: nil) .
        instantiateViewControllerWithIdentifier("\(color)ViewController")
}

我写了类似的东西:

private(set) lazy var orderedViewControllers: [UIViewController] = {
    return [self.newPagedViewController("TutorialViewController1"),
        self.newPagedViewController("TutorialViewController2"),
        self.newPagedViewController("TutorialViewController3"),
        self.newPagedViewController("TutorialViewController4"),
        self.newPagedViewController("TutorialViewController5")]
}()

private func newPagedViewController(name: String) -> UIViewController {

    return UIStoryboard(name: "Main", bundle: nil) .
        instantiateViewControllerWithIdentifier("\(name)")
}

它可以工作,但它创建了5个控制器,每个控制器都有白色背景。 如何实现一个功能,每个创建的PageViewController都有我的自定义代码设置的背景:

let background = CAGradientLayer().greenBlue()
    background.frame = self.view.bounds
    self.view.layer.insertSublayer(background, atIndex: 0)

我试着把这段代码放进去:

private func newPagedViewController(name: String) -> UIViewController {

 let background = CAGradientLayer().greenBlue()
    background.frame = self.view.bounds
    self.view.layer.insertSublayer(background, atIndex: 0)

    return UIStoryboard(name: "Main", bundle: nil) .
        instantiateViewControllerWithIdentifier("\(name)")
}

但它没有做到这一点,背景保持白色......我该如何解决?

1 个答案:

答案 0 :(得分:0)

尝试更改实例化视图控制器的颜色:

private func newPagedViewController(name: String) -> UIViewController {

   let vc = UIStoryboard(name: "Main", bundle: nil) .
    instantiateViewControllerWithIdentifier("\(name)")

   vc.view.backgroundColor = UIColor(red: 25/255.0, green: 134/255.0, blue: 125/255.0, alpha: 1)


   return vc
}