2014-10-20 54 views
0

我希望在應用輸入或即將進入背景時更改圖像。如何在應用即將進入背景時更改UIImage - swift

文件名AppDelegate.swift

func applicationWillResignActive(application: UIApplication) { 
    ViewController().changeImg();   
} 

文件名ViewController.swift

func changeImg(){ 
    backgroundImg.image = UIImage(named: "blue") as UIImage; 
} 

但我代一個錯誤

fatal error: unexpectedly found nil while unwrapping an Optional value 

回答

0

這一行

ViewController().changeImg() 

您正在實例化一個新的空的ViewController,它沒有changeImg方法。您需要對您的自定義viewController的引用。

如果是的viewController你RootViewController的,你可以通過

// create a property in appDelegate for your viewController 
var viewController: ViewController? 


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { 

    let navigationController = application.windows[0].rootViewController as UINavigationController 
    viewController = navigationController.viewControllers[0] as ViewController 
} 

在你的appDelegate找到它,那麼你可以調用

viewController?.changeImg() 
+0

我看,我該怎麼辦呢? – Ben 2014-10-20 11:18:56

+0

我已經更新我的答案 – zisoft 2014-10-20 11:22:37

+0

讓navigationController = application.windows [0] .rootViewControlle爲UINavigationController的 self.viewController = navigationController.viewControllers [0]視圖控制器 – Ben 2014-10-20 11:25:06

相關問題