fix: make windowWidth and windowHeight of SceneDelegate observable (#1693)

This commit is contained in:
Thai D. V 2023-12-03 18:43:15 +07:00 committed by GitHub
parent bf65c386e6
commit 56360ae821
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,16 +1,11 @@
import Combine
import UIKit
@Observable public class SceneDelegate: NSObject, UIWindowSceneDelegate {
@Observable
public class SceneDelegate: NSObject, UIWindowSceneDelegate, Sendable {
public var window: UIWindow?
public var windowWidth: CGFloat {
window?.bounds.size.width ?? UIScreen.main.bounds.size.width
}
public var windowHeight: CGFloat {
window?.bounds.size.height ?? UIScreen.main.bounds.size.height
}
public private(set) var windowWidth: CGFloat = UIScreen.main.bounds.size.width
public private(set) var windowHeight: CGFloat = UIScreen.main.bounds.size.height
public func scene(_ scene: UIScene,
willConnectTo _: UISceneSession,
@ -26,4 +21,36 @@ import UIKit
}
#endif
}
public override init() {
super.init()
self.windowWidth = self.window?.bounds.size.width ?? UIScreen.main.bounds.size.width
self.windowHeight = self.window?.bounds.size.height ?? UIScreen.main.bounds.size.height
Self.observedSceneDelegate.insert(self)
_ = Self.observer // just for activating the lazy static property
}
deinit {
Task { @MainActor in
Self.observedSceneDelegate.remove(self)
}
}
private static var observedSceneDelegate: Set<SceneDelegate> = []
private static let observer = Task {
while true {
try? await Task.sleep(for: .seconds(0.1))
for delegate in observedSceneDelegate {
let newWidth = delegate.window?.bounds.size.width ?? UIScreen.main.bounds.size.width
if delegate.windowWidth != newWidth {
delegate.windowWidth = newWidth
}
let newHeight = delegate.window?.bounds.size.height ?? UIScreen.main.bounds.size.height
if delegate.windowHeight != newHeight {
delegate.windowHeight = newHeight
}
}
}
}
}