SwiftUI 获取屏幕尺寸

bounds

1
var screenBounds:CGRect = UIScreen.main.bounds

bounds 得到的是单位为点(point)的尺寸。

1
2
var width: CGFloat = UIScreen.main.bounds.width
var height: CGFloat = UIScreen.main.bounds.height

这样就可以得到 CGFloat 格式的数据,可以使用该值进行一些绘制界面,比如画格子之类的、移动组件的位置。

之所以该格式的数据被用于绘图、移动组件的位置是因为 View 一般都是使用 CGFloat 格式的数据来进行操作的,如果使用 nativeBounds 是没办法来进行操作的,因为点(point)和像素(pixel)不是一一对应的。并且由于范围稍微“宽松”一些,这样可以有效避免因为计算时四舍五入导致的误差。

nativeBounds

1
var screenBounds: CGRect = UIScreen.main.nativeBounds

nativeBounds得到的是单位为像素(pixel)的尺寸。

1
2
var width: CGFloat = UIScreen.main.nativeBounds.width
var height: CGFloat = UIScreen.main.nativeBounds.height

这样就可以得到CGFloat格式的数据,一般用于返回屏幕尺寸或者某个组件的像素值。绘制、移动组件一般不用这个数据。

NSScreen

macOS 不支持 UIScreen 而是采用 NSScreen。

1
2
3
var window = NSScreen.main?.visibleFrame

// 在 macOS 中,visibleFrame 属性返回的是屏幕的可见区域,不包括菜单栏和 Dock 的高度。这对于开发者来说,在确定窗口或视图的显示位置时非常有用,可以避免窗口被系统 UI 元素遮挡。

使用

1
2
Text("")
.frame(width: window!.width / 2.0, height: window!.height / 1.5)

SwiftUI 获取屏幕尺寸
https://wonderhoi.com/2025/06/25/SwiftUI-获取屏幕尺寸/
作者
wonderhoi
发布于
2025年6月25日
许可协议