Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

ios - UIWindow? does not have member named bounds

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...