获取屏幕宽高
- Published on
- Authors
- Name
- Wxm
在 ios 中如果需要做一些页面,如抽屉侧边栏,就需要获得屏幕宽度,那么如何获取呢?
以下是两种方式:
通过 GeometryReader 获取
GeometryReader
包装器提供了对父视图几何信息的访问,从而使你能够根据视图的实际大小来设置内容,当设备横置或者纵置,也会跟随动态调整。
struct ContentView: View {
var body: some View {
GeometryReader { geo in
Text("Screen Width: \(geo.size.width)")
}
}
}
通过 UIScreen 获取
UIScreen.main.bounds 将返回设备的逻辑宽度,不考虑横置或纵置的情况,包含 width 和 height 等信息,如果需要获取实际物理宽高 也可以使用 UIScreen.main.nativeBounds.width
// 通过 UIScreen.main.bounds.width 来获得宽度
struct ContentView: View {
var body: some View {
Text("Screen Width: \(UIScreen.main.bounds.width)")
}
}
总结
如果需要考虑横纵就必须使用 GeometryReader 其他情况就随意喽。