SwiftUI 单向自定义下拉菜单

SwiftUI Custom Dropdown in one direction

我正在尝试在 SwiftUI 中制作自定义下拉栏。它看起来像这样:

VStack{
   Text("Dropdown").onTapGesture{
      self.expand.toggle()
   }
   if expand {
      Text("Dropdown Item 1")
      Text("Dropdown Item 2")
   }
}
.padding(10)
.background(.green)
.cornerRadius(10)
.animation(.spring())

Expand 是一个 @State var 变量。

当前的问题是,当单击 Text("Dropdown") 时,VStack 会双向展开。有没有办法让VStack只向下扩展?

这可能取决于整体布局,但在您提供的代码快照中,可以通过更改对齐指南来解决,如下面的演示

VStack{
    Text("Dropdown").onTapGesture{
        self.expand.toggle()
    }
    if expand {
        Text("Dropdown Item 1")
        Text("Dropdown Item 2")
    }
}
.padding(10)
.background(Color.green)
.cornerRadius(10)
.animation(.spring())
.alignmentGuide(VerticalAlignment.center) { [=10=][.top] }    // << here !!