描述图片

获取屏幕宽高

Published on
Authors
  • Name
    Wxm
    Twitter

在 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 其他情况就随意喽。

0:00/0:00

Nujabes - Blessing It -remix (feat.Substantial & Pase Rock from Five Deez)

Nujabes - Horn in the middle

Nujabes - Lady Brown (feat. Cise Starr from CYNE)

Nujabes - Kumomi

Nujabes - Highs 2 Lows (feat.Cise Starr from CYNE)

Nujabes - Beat laments the world

Nujabes - Letter from Yokosuka

Nujabes - Think Different (feat.Substantial)

Nujabes - Next view (feat. Uyama Hiroto)

Nujabes - Latitude -remix (feat.Five Deez)

Nujabes - F.I.L.O. (feat. Shing02)

Nujabes - Summer Gypsy

Nujabes - The Final View

Nujabes - Peaceland