I want to get the window bounds as CGRect
object.
This is my current code:
let screenSize : CGRect = self.view.window?.frame
I found this code on the internet, but sometimes screenSize
is nil.
Is there any other option?
I want to get the window bounds as CGRect
object.
This is my current code:
let screenSize : CGRect = self.view.window?.frame
I found this code on the internet, but sometimes screenSize
is nil.
Is there any other option?
if let window = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first {
let screenFrame = window.frame
}
You can get the sizes from the screenFrame
UIView
has a property called window
, which is called nil
until the view is added to the window. Get the frame
when the window
property is not nil
. So, in the experiment below, the view.window
value is not nil
only when entering viewWillLayoutSubviews
.
https://eunjin3786.tistory.com/96
Sorry, I couldn't find a good example in English. In this experiment, the author marked the blue title at the time when view.window
was not nil
.
iOS 15 deprecated the aforementioned solutions. Here's a new syntax that should be up to date, safe and actually work on split screen iPad.
let windowSize = UIApplication.shared.connectedScenes
.compactMap({ scene -> UIWindow? in
(scene as? UIWindowScene)?.keyWindow
})
.first?
.frame
.size
You can get the height and width separately by typing:
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height