创建一个具有配置视图的函数的类 - swift

时间:2015-02-23 14:19:15

标签: ios swift

我创建了这个类来配置每个视图控制器以避免viewdidload()中的冗余。

class Configuration: UIViewController  {

    func setNavigationTheme(#backgroundImage: String, dashboardImage: String) {

        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: dashboardImage), forBarMetrics: UIBarMetrics.Default)
        self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
        let bgImage: UIImage = UIImage(named: backgroundImage)!
        self.view.backgroundColor = UIColor(patternImage: bgImage)

    }

}

在viewDidLoad()

var configure = Configuration()
configure.setNavigationTheme(backgroundImage: "Background", dashboardImage: "Dashboard")

当我调用该函数时,它不会改变任何东西,我是否做错了?

1 个答案:

答案 0 :(得分:1)

您需要使用Configuration类扩展视图控制器。

    class MyViewController: Configuration {

    override func viewDidLoad() {
        //Don't initialize new Configuration class.
        setNavigationTheme(backgroundImage: "Background", dashboardImage: "Dashboard")

    }
}

您的配置类:

class Configuration: UITableViewController  {

    func setNavigationTheme(#backgroundImage: String, dashboardImage: String) {

        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: dashboardImage), forBarMetrics: UIBarMetrics.Default)
        self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
        let bgImage: UIImage = UIImage(named: backgroundImage)!
        self.view.backgroundColor = UIColor(patternImage: bgImage)

    }

}