๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐ŸŽ iOS/SwiftUI

[iOS] SwiftUI - GeometryReader / View ํฌ๊ธฐ์™€ ์ขŒํ‘œ ๊ณ„์‚ฐํ•˜๊ธฐ

by Danna 2023. 10. 21.
728x90
728x90

https://developer.apple.com/documentation/swiftui/geometryreader
์Šค์œ  ๊ณต๋ถ€ํ•˜๊ธฐ ๐Ÿง

GeometryReader

GeometryReader ๋Š” ์ปจํ…์ธ ์˜ ํฌ๊ธฐ์™€ ์œ„์น˜๋ฅผ ํ•จ์ˆ˜๋กœ ๋‚˜ํƒ€๋‚ด๋Š” ์ปจํ…Œ์ด๋„ˆ ๋ทฐ๋กœ, ๋ถ€๋ชจ ๋ทฐ์˜ ์‚ฌ์ด์ฆˆ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

  • ์ผ๋ฐ˜์ ์œผ๋กœ๋Š” HStack, VStack, ZStack ์„ ์‚ฌ์šฉํ•ด์„œ ๋ ˆ์ด์•„์›ƒ์„ ๋ฐฐ์น˜ํ•˜์ง€๋งŒ,
  • UIKit ์„ ๊ฐ™์ด ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ํ˜น์€ ์„ธ๋ถ€์ ์ธ ์กฐ์ •์ด ํ•„์š”ํ•  ๊ฒฝ์šฐ ์‚ฌ์šฉํ•  ๊ฒƒ์œผ๋กœ ๋ณด์ด๋„ค์š” ๐Ÿ‘€
  • View ์˜ ํฌ๊ธฐ๋‚˜ ์ขŒํ‘œ๋ฅผ ๊ณ„์‚ฐํ•˜๊ณ  ์‹ถ์„๋•Œ ํ™œ์šฉ๋„ ๊ฐ€๋Šฅํ•ด๋ณด์ž…๋‹ˆ๋‹ค! ๐Ÿค”

GeometryReader ์‚ฌ์šฉํ•ด์„œ ๋ ˆ์ด์•„์›ƒ ๋ฐฐ์น˜ํ•ด๋ณด๊ธฐ

  • GeometryReader ์ƒ์„ฑ์ž์˜ ํด๋กœ์ € ์ธ์ž๋Š” GeometryProxy ๋กœ ๋˜์–ด์žˆ์Šต๋‹ˆ๋‹ค.

  • GeometryProxy ๊ฐ์ฒด์— ์ ‘๊ทผํ•ด์„œ size, safeAreaInsets ๋ณ€์ˆ˜์™€ frame(in:) ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
    • size : ์ปจํ…Œ์ด๋„ˆ ๋ทฐ์˜ ํฌ๊ธฐ
    • safeAreaInsets : ์ปจํ…Œ์ด๋„ˆ ๋ทฐ์˜ safe area inset
    • frame(in:) : ์ปจํ…Œ์ด๋„ˆ๋ทฐ์˜ frame

safeAreaInsets

  • ์ปจํ…Œ์ด๋„ˆ ๋ทฐ๊ฐ€ safeArea ์ด๋ž‘ ๋ถ™์–ด์žˆ๋Š” ๊ฒฝ์šฐ์—๋งŒ ์ธก์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    • ์•„๋ž˜ ์˜ˆ์‹œ์ฒ˜๋Ÿผ VStack ์œผ๋กœ ์ƒ๋‹จ์— ๋‹ค๋ฅธ ๋ทฐ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ์— ์ƒ๋‹จ์˜ ๊ฐ’์€ 0์œผ๋กœ ๋œน๋‹ˆ๋‹ค!
    • EdgeInsets(top: 0.0, leading: 0.0, bottom: 34.0, trailing: 0.0)

frame(in:)

func frame(in coordinateSpace: CoordinateSpace) -> CGRect

  • ์œ„์˜ ๋ฉ”์†Œ๋“œ๋Š” iOS 17.0 ์—์„œ deprecated

func frame(in coordinateSpace: some CoordinateSpaceProtocol) -> CGRect

  • CoordinateSpaceProtocol ๋Š” ๋ฒ ํƒ€์—์„œ๋ถ€ํ„ฐ ์‚ฌ์šฉ๊ฐ€๋Šฅ์ด์ง€๋งŒ, ๋‚ด๋ถ€์— global, local, named ๋Š” ์‚ฌ์šฉ๊ฐ€๋Šฅํ•ด๋ณด์ž…๋‹ˆ๋‹ค!
  • CoordinateSpace ๋Š” ๋ทฐ์˜ ์ขŒํ‘œ ๊ณต๊ฐ„์œผ๋กœ, ์ผ๋ฐ˜์ ์œผ๋กœ .global, .local, .named(AnyHashable) ์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
    • .global : ๋ฃจํŠธ ๋ทฐ(์ „์ฒด ํ™”๋ฉด)์˜ ์ขŒํ‘œ ๊ณต๊ฐ„
    • .local : ํ˜„์žฌ ๋ทฐ์˜ ์ขŒํ‘œ ๊ณต๊ฐ„
    • .named(AnyHashable) : ํŠน์ •ํ•œ ๋ทฐ์— ์ด๋ฆ„์„ ๋ถ™์ด๊ณ , ํ•ด๋‹น ๋ทฐ์—์„œ ๋ดค์„๋•Œ์˜ ์ขŒํ‘œ ๊ณต๊ฐ„
  • ์ฝ”๋“œ๋กœ ํ™•์ธํ•ด๋ณด๋ฉด ๊ฐ๊ฐ ๋‹ค๋ฅธ๊ฑธ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!
struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello!")

            GeometryReader { geometry in
                Text("Hello!")
                    .frame(
                        width: geometry.frame(in: .global).width,
                        height: geometry.frame(in: .global).height / 2
                    )
                    .background(Color.blue)
                    .onAppear {
                        print("\(geometry.frame(in: .global))")
                        print("\(geometry.frame(in: .local))")
                        print("\(geometry.frame(in: .named("test")))")
                    }
            }

            Text("Hello!")
                .coordinateSpace(name: "test")
        }
    }
}
728x90
728x90