2015-02-23 33 views
0

我创建这个类来配置每个视图控制器,以避免viewdidload()内部的冗余。创建一个类与一个函数来配置视图看 - swift

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

你需要扩展你的视图控制器与你的配置类。

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) 

    } 

} 
+0

我怎么适应这里 “类ActivityTableViewController:的UITableViewController” 应该不是我创建一个协议? – shaideru 2015-02-23 15:27:26

+0

只需使用“class Configuration:UITableViewController {...)”而不是“class Configuration:UIViewController {...}”更改您的配置类,我编辑了我的答案 – gellezzz 2015-02-23 15:37:00

+0

它的工作原理!但我如何将这个应用到UIViewController和其他控制器? – shaideru 2015-02-23 16:11:02