Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why geometry reader doesn't center its child?

red border is geometry Area and black border is text area

currently using Xcode12 Beta 3

struct Testing_Geometry_: View {
    var body: some View {
        GeometryReader { geo in
            Text("Hello, World!")
                .border(Color.black)
        }
        .border(Color.red)
    }
}

I wanted to position text in center with this code

struct Testing_Geometry_: View {
    var body: some View {
        GeometryReader { geo in
            Text("Hello, World!")
                .position(x:geo.frame(in:.global).midX,y:geo.frame(in:.global).midY)
                .border(Color.black)
        }
        .border(Color.red)
    }
}

but I got this result which means Text is taking the whole geometry size and I think it's not correct! cause texts has to fit in their space

three roles suggested by @twostraws for layout systems are

1- parent offers its size

2-child chooses its size

3-parent positions its child

but I think this isn't right!

text is taking the whole geometry space

like image 343
amin torabi Avatar asked Dec 31 '22 23:12

amin torabi


1 Answers

If someone is looking for basic solution, you can put it in one of Stack and make it use whole size of geometry size with alignment center. That will make all elements underneath to use correct size and aligned in center

GeometryReader { geometry in
    ZStack {
        // ... some of your views
    }
    .frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
}
like image 162
green0range Avatar answered Jan 08 '23 10:01

green0range