2015-02-23 15 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