SwiftUI 以多平台形式获取屏幕大小

Kev*_*OUX 5 ios swiftui

实际上,我在我的ContentView.swift文件中使用

UIScreen.main.bounds.size.width 
Run Code Online (Sandbox Code Playgroud)

获取宽度屏幕的大小。不幸的是,我不能在 MacOS 目标上使用它,因为它需要NSScreen

NSScreen.main.bounds.size.width
Run Code Online (Sandbox Code Playgroud)

是否有任何通用Screen来获取屏幕尺寸?

Fab*_*yne 8

为了解决这个问题,我所做的是创建一个具有平台条件的类。

class SGConvenience{
    #if os(watchOS)
    static var deviceWidth:CGFloat = WKInterfaceDevice.current().screenBounds.size.width
    #elseif os(iOS)
    static var deviceWidth:CGFloat = UIScreen.main.bounds.size.width
    #elseif os(macOS)
    static var deviceWidth:CGFloat? = NSScreen.main?.visibleFrame.size.width // You could implement this to force a CGFloat and get the full device screen size width regardless of the window size with .frame.size.width
    #endif
}
Run Code Online (Sandbox Code Playgroud)

然后我在需要时简单地调用 SGConvenience.deviceWidth