I need to get informations about the screen size for the current scene in an iPad application. Assume this snippet as an example
var body: some View {
let sceneSize = getCurrentSceneSize()
Rectangle()
.fill(.red)
.frame(height: 200)
.frame(maxWidth: .infinity)
.overlay {
Text("\(sceneSize.width, specifier: "%.0f")x\(sceneSize.height, specifier: "%.0f")")
.font(.headline)
.foregroundColor(.white)
}
}
}
func getCurrentSceneSize() -> CGSize {
return UIApplication
.shared
.connectedScenes
.compactMap { ($0 as? UIWindowScene)?.keyWindow }
.last?
.frame.size ?? .zero
}
I got the getCurrentSceneSize
implementation from this answer, and most of the times it seems to work, where most of the times means:
- There is a single instance of the app running.
- The app is opened as a split view, and it doesn't get resized (the split view's thumb isn't dragged).
However this code appears to break when:
- The app is opened as a split view and it gets resized through the thumb, in this case the update isn't triggered unless both the split views are instances of my app.
- If both the split views are instances of my app, each instance gets its size correctly updated, unless I close it and open it from background, in which case both instances think their width is 1/3 of the screen width.
- When used with Stage Manager, the size isn't updated when passing to full screen mode, and the other way around.
So my question is: is there any way to reliably get the updated scene size that works across iOS and iPadOS?