实际上,我在我的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
来获取屏幕尺寸?
为了解决这个问题,我所做的是创建一个具有平台条件的类。
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