Home > AI > IOS > SwiftUI >

GeometryReader

Example 1:

struct SubView: View {
    
    var body: some View {
        GeometryReader { geometry in
            HStack(spacing: 0) {
                Text("Left")
                    .frame(width: geometry.size.width / 2, height: geometry.size.height)
                    .background(Color.yellow)
                Text("Right")
                    .frame(width: geometry.size.width / 2, height: geometry.size.height)
                    .background(Color.orange)
            }
        }
    }
}


struct ContentView: View {
    var body: some View {
        GeometryReader(content: { geometry in
            SubView()
                .frame(width: geometry.size.width / 2, height: geometry.size.height / 10, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
        })
    }
}

Example 2: size

struct ContentView: View {
    var body: some View {
        GeometryReader { geo in
           
            HStack {
                Spacer()
                
                Text("Hello, World!")
                    .frame(width: geo.size.width * 0.9)
                    .background(Color.red)
                
                Spacer()
            }
            
        }
    }
}

Example 3: GeometryReader looks like will fill all remaining space.

struct ContentView: View {
    var body: some View {
        HStack(spacing:0) {
            Text("left")
                .background(Color.blue)
            GeometryReader {geo in
                Text("right")
                    .background(Color.orange)
            }
            .background(Color.green)
        }
        .edgesIgnoringSafeArea(.all)
    }
}

Example 4: coordinate system

struct OuterView: View {
    var body: some View {
        VStack {
            Text("Top")
            InnerView()
                .background(Color.green)
            Text("Bottom")
        }
    }
}

struct InnerView: View {
    var body: some View {
        HStack {
            Text("Left")
            GeometryReader { geo in
                Text("Center")
                    .background(Color.blue)
                    .onTapGesture {
                        print("Global center: \(geo.frame(in: .global).midX) x \(geo.frame(in: .global).midY)")
                        print("Custom center: \(geo.frame(in: .named("Custom")).midX) x \(geo.frame(in: .named("Custom")).midY)")
                        print("Local center: \(geo.frame(in: .local).midX) x \(geo.frame(in: .local).midY)")
                    }
            }
            .background(Color.orange)
            Text("Right")
        }
    }
}

struct ContentView: View {
    var body: some View {
        OuterView()
            .background(Color.red)
            .coordinateSpace(name: "Custom")
    }
}

Leave a Reply