Can't unwrap Optional.None when setting window background color

点点圈 提交于 2019-12-23 03:41:25

问题


I think I'm missing something very simple here...

override func viewDidLoad() {
    self.view.window.backgroundColor = NSColor.grayColor();                            
}

This returns

fatal error: Can't unwrap Optional.None

which isn't a very descriptive error. Can someone tell me what I'm missing?


回答1:


Something in the self.view.window.backgroundColor chain (probably self.view.window) is nil. Many view- and view controller-related properties are implemented as implicitly unwrapped, which means that they are Optionals that you can treat like non-Optional variables for convenience's sake. Unfortunately, if you try to access one when it's nil you get the runtime error you're seeing.

Can you set the background color of the view's layer instead? view.window is nil when a view hasn't been added to a window, but view.layer should be there regardless.



来源:https://stackoverflow.com/questions/24132010/cant-unwrap-optional-none-when-setting-window-background-color

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!