4

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Daisy the cat
  • 372
  • 3
  • 11

5 Answers5

3
if let window = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first {
   let screenFrame = window.frame
}

You can get the sizes from the screenFrame

1

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.

Munok Kim
  • 70
  • 1
  • 5
1

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
Clément Cardonnel
  • 4,232
  • 3
  • 29
  • 36
-1

You can get the height and width separately by typing:

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
-4

I've found the answer

let screenSize : CGRect = self.view.frame
Daisy the cat
  • 372
  • 3
  • 11