UIWindow? does not have member named bounds

2019-01-20 00:16发布

I'm trying to update PKHUD (https://github.com/pkluz/PKHUD) to work with Xcode 6 beta 5 and am almost through except for one tiny detail:

internal class Window: UIWindow {
    required internal init(coder aDecoder: NSCoder!) {
        super.init(coder: aDecoder)
    }

    internal let frameView: FrameView
    internal init(frameView: FrameView = FrameView()) {
        self.frameView = frameView

        // this is the line that bombs
        super.init(frame: UIApplication.sharedApplication().delegate.window!.bounds)

        rootViewController = WindowRootViewController()
        windowLevel = UIWindowLevelNormal + 1.0
        backgroundColor = UIColor.clearColor()

        addSubview(backgroundView)
        addSubview(frameView)
    }
    // more code here
}

Xcode gives me the error UIWindow? does not have a member named 'bounds'. I'm pretty sure this is a trivial mistake related to type-casting, but I've been unable to find the answer to this for a couple hours.

Also, this error occurs only in Xcode 6 beta 5, which means that the answer lies in something Apple changed recently.

All help is greatly appreciated.

1条回答
够拽才男人
2楼-- · 2019-01-20 00:50

The declaration of the window property in the UIApplicationDelegate protocol changed from

optional var window: UIWindow! { get set } // beta 4

to

optional var window: UIWindow? { get set } // beta 5

which means that it is an optional property yielding an optional UIWindow:

println(UIApplication.sharedApplication().delegate.window)
// Optional(Optional(<UIWindow: 0x7f9a71717fd0; frame = (0 0; 320 568); ... >))

So you have to unwrap it twice:

let bounds = UIApplication.sharedApplication().delegate.window!!.bounds

or, if you want to check for the possibility that the application delegate has no window property, or it is set to nil:

if let bounds = UIApplication.sharedApplication().delegate.window??.bounds {

} else {
    // report error
}

Update: With Xcode 6.3, the delegate property is now also defined as an optional, so the code would now be

let bounds = UIApplication.sharedApplication().delegate!.window!!.bounds

or

if let bounds = UIApplication.sharedApplication().delegate?.window??.bounds {

} else {
    // report error
}

See also Why is main window of type double optional? for more solutions.

查看更多
登录 后发表回答