SwiftUI GeometryReader does not layout custom subviews in center

后端 未结 3 445
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-17 18:59

I have a custom view:

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


        
相关标签:
3条回答
  • 2021-01-17 19:36

    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)
        }
    }
    
    0 讨论(0)
  • 2021-01-17 19:37

    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()
           }
        }
    }
    
    0 讨论(0)
  • 2021-01-17 19:49

    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

    0 讨论(0)
提交回复
热议问题