[Ch20] Using GeometryReader

shintwelv·2022년 8월 3일
0

GeometryReader enables automatically adapting to different screen sizes
Use GeometryReader's relative coordinates

Understanding the GeometryReader

can hold multiple views
expands to take up as much space as possible
can retrieve its width and height

GeometryReader{ geometry in
            VStack{
                Text("Width = \(geometry.size.width)")
                Text("Height = \(geometry.size.height)")
            }
        }.background(.yellow)

on iPod touch

on iPad 9th

Understanding the Differences Between Global and Local coordinates

Coordinates within the GeometryReader are known as local coordinates.
Global coordinates refer to the entire iOS screen.

Global coordinates always differ between different iOS device screens, local coordinates with a GeometryReader always remains consistent.

        VStack{
            Text("This Text view pushed the GeometryReader down")
            HStack{
                Text("Pushed to the right")
                GeometryReader{ geometry in
                    VStack{
                        Text("Local x origin = \(geometry.frame(in: .local).origin.x)")
                        Text("Local y origin = \(geometry.frame(in: .local).origin.y)")
                        Text("Global x origin = \(geometry.frame(in: .global).origin.y)")
                        Text("Global y origin = \(geometry.frame(in: .global).origin.y)")
                    }
                }.background(.yellow)
                    .ignoresSafeArea()
            }
        }

Identifying Minimum, Mid, and Maximum Values of a GeometryReader

top-left of a device's screen is minX and minY

  • Global coordinates
    Maximum X and Y have different value when screen size changes
    Using global coordinates to position view could cut off the view on smaller screen
  • Local coordinates within GeometryReader
    adapt to different screen sizes
    Instead of using fixed value for positioning, use maxX, maxY or other values.
GeometryReader{ geometry in
            VStack{
                Text("minX = \(geometry.frame(in: .local).minX)")
                Text("midX = \(geometry.frame(in: .local).midX)")
                Text("maxX = \(geometry.frame(in: .local).maxX)")
                Divider()
                Text("minY = \(geometry.frame(in: .local).minY)")
                Text("midY = \(geometry.frame(in: .local).midY)")
                Text("maxY = \(geometry.frame(in: .local).maxY)")
            }
        }.background(.yellow)

on iPod touch

on iPad 9th

Summary

  • Using global coordinates
    upper left of the screen is (0,0)
  • Using local coordinates within GeometryReader
    upper left of the GeometryReader is (0,0), no matter where the GeometryReader is positioned

0개의 댓글