英文:
How do I get `UIScreen.main.scale` after iOS 16
问题
UIScreen.main.scale
将被弃用。以下是UIKit.UIScreen文档中的内容:
@available(iOS, introduced: 2.0, deprecated: 100000, message: "Use a UIScreen instance found through context instead: i.e, view.window.windowScene.screen")
open class var main: UIScreen { get } // 设备的内部屏幕
deprecated: 100000
表示将被弃用。
所以我的问题是,我应该如何替换这个方法?
在主要的应用程序中,可以使用以下方法,但在扩展应用程序中 UIApplication.shared
不可用。是否有解决此问题的解决方案?
@available(iOSApplicationExtension, unavailable)
extension UIWindow {
static var current: UIWindow? {
for scene in UIApplication.shared.connectedScenes {
guard let windowScene = scene as? UIWindowScene else { continue }
for window in windowScene.windows {
if window.isKeyWindow { return window }
}
}
return nil
}
}
@available(iOSApplicationExtension, unavailable)
extension UIScreen {
static var current: UIScreen? {
UIWindow.current?.screen
}
}
英文:
UIScreen.main.scale
will deprecated.
here it the document in UIKit.UIScreen
@available(iOS, introduced: 2.0, deprecated: 100000, message: "Use a UIScreen instance found through context instead: i.e, view.window.windowScene.screen")
open class var main: UIScreen { get } // the device's internal screen
deprecated: 100000
means to be deprecated.
So my question is how do I replace this method?
use below method can work in main App, but UIApplication.shared
doesn't available in extension app. Is there any solution to resolve this problem
@available(iOSApplicationExtension, unavailable)
extension UIWindow {
static var current: UIWindow? {
for scene in UIApplication.shared.connectedScenes {
guard let windowScene = scene as? UIWindowScene else { continue }
for window in windowScene.windows {
if window.isKeyWindow { return window }
}
}
return nil
}
}
@available(iOSApplicationExtension, unavailable)
extension UIScreen {
static var current: UIScreen? {
UIWindow.current?.screen
}
}
答案1
得分: 1
extension UIViewController {
func screen() -> UIScreen? {
var parent = self.parent
var lastParent = parent
while parent != nil {
lastParent = parent
parent = parent!.parent
}
return lastParent?.view.window?.windowScene?.screen
}
}
在以下位置使用此扩展:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let screen = windowScene.screen
}
英文:
extension UIViewController {
func screen() -> UIScreen? {
var parent = self.parent
var lastParent = parent
while parent != nil {
lastParent = parent
parent = parent!.parent
}
return lastParent?.view.window?.windowScene?.screen
}
}
and use this extension in
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let screen = windowScene.screen
check this link for reference
https://stackoverflow.com/questions/74458971/correct-way-to-get-the-screen-size-on-ios-after-uiscreen-main-deprecation
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论