如何在SwiftUI中根据GeometryReader的子级高度设置其高度?

时间:2019-10-18 15:14:27

标签: swift swiftui

在我的SwiftUI应用程序中,我有一个VStack(VStack 1)容器,可以全屏显示高度。在此VStack中,我有另一个VStack(VStack 2),它根据其子级(文本)获得高度,我想将其放在该父级(VStack 1)的底部。在VStack 2上,我需要放置GeometryReader以获取VStack的高度(VStack 2)。问题是GeometryReader自动获得全屏高度。因此,VStack 2放置在屏幕中间。不是我想要的我不知道是否可以将GeometryReader的高度设置为与VStack 2相同的高度?

我的测试代码:

import SwiftUI

struct ContentView: View {
  var body: some View {
    VStack {
      GeometryReader { geometry in
        VStack {
           Text("Text n°1")
           Text("Text n°2")
           Text("Text n°3")
           Text("Text n°4")
        }
        .border(Color(.red))
      }
      .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: nil, alignment: .bottom)
      .border(Color(.black))
    }
    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .bottom)
  }
}

结果:

Screenshot

我想要的

Result I need

谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我认为您使用GeometryReader使其过于复杂。您是否尝试过仅使用Spacer()

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Haha")
            Spacer()
            VStack {
                Text("1")
                Text("2")
                Text("3")
            }
        }
    }
}

答案 1 :(得分:1)

以下是在使用GeometryReader时将子视图高度设置为父视图

enter image description here

import SwiftUI

struct ContentView: View {
    
    @State private var totalHeight = CGFloat(100) // no matter - just for static Preview !!
    
    var body: some View {
        HStack(alignment:.top) {
            Text("Title 1")
            GeometryReader { geo in
                VStack(spacing: 10) {
                    Text("Subtitle 1")
                        .frame(maxWidth: .infinity)
                    Text("Subtitle 2")
                        .frame(maxWidth: .infinity)
                    Text("Subtitle 3")
                        .frame(maxWidth: .infinity)
                }
                .background(Color.blue)
                .frame(width: geo.size.width * 0.6)
                .background(GeometryReader {gp -> Color in
                    DispatchQueue.main.async {
                        // update on next cycle with calculated height of ZStack !!!
                        self.totalHeight = gp.size.height
                    }
                    return Color.clear
                })
            }
            .background(Color.yellow)
        }
        .frame(maxWidth: .infinity)
        .frame(height: totalHeight)
        .background(Color.green)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Ref-https://stackoverflow.com/a/61315678/815864