SwiftUI GeometryReader does not layout custom subviews in center

两盒软妹~` 提交于 2020-07-30 06:09:38

问题


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?


回答1:


Try the following (built-in container by default expanded to size of GeometryReader and have explicit default alignment set to center by both dimensions). Tested with Xcode 11.2.

var body: some View {
    GeometryReader { geometry in
       VStack { // explicit container with center default alignment
        ImageContent()
       }
    }
}



回答2:


for what do you need GeometryReader, if you don't use the provided GeometryProxy values?

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            ImageContent()
                .position(x: geometry.size.width / 2, y: geometry.size.height / 2)
        }
    }
}

will define the exact position based on value provided




回答3:


I'm not sure why this is happening but you can use what others have suggested, or use the midX and midY comes 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)
    }
}


来源:https://stackoverflow.com/questions/60373719/swiftui-geometryreader-does-not-layout-custom-subviews-in-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!