Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI GeometryReader does not layout custom subviews in center

I have a custom view:

struct ImageContent: View {
    var body: some View {
        Image("smile")
            .resizable()
            .scaledToFit()
    }
}

Which is being placed into another view with a GeometryReader:

var body: some View {
    GeometryReader { geometry in
        ImageContent()
        //Image("smile").resizable().scaledToFit()
    }
}

The problem is, the ImageContent view is not centered on the screen, it is being placed on the top, however, by removing the ImageContent subview and directly adding the view's content into the geometry reader will fix the issue (see picture).

Also, removing the GeometryReader can fix the issue as well.

I need the subview because I will be implementing some additional logic, and also need the GeometryReader because there is a gesture added to the Image that uses it.

Any idea?

Screenshot

like image 788
Tom Shen Avatar asked Feb 24 '20 10:02

Tom Shen


Video Answer


1 Answers

I'm not sure why this is happening but you can use what others have suggested, or use the midX and midY from GeometryProxy's frame. Like the following:

var body: some View {
    GeometryReader { geometry in
        ImageContent()
        .position(x: geometry.frame(in: .local).midX, y: geometry.frame(in: .local).midY)
    }
}
like image 50
MEnnabah Avatar answered Oct 01 '22 20:10

MEnnabah