ScrollView 导致 SwiftUI 中的按钮有问题

Mar*_*Aba 5 scrollview swift swiftui

我一直在尝试在 SwiftUI 中创建一个表单,但由于使用“Form()”的限制,我选择使用包含按钮的 ForEach 循环创建一个 ScrollView。当我运行该项目并尝试单击按钮时,它会单击不正确的按钮,除非我滚动视图。我是 SwiftUI 的新手,我无法弄清楚。

我尝试制作不同大小的 ScrollView,但似乎没有关系

struct DropDown: View {

var datos: [String]
var categoria: String

@State var titulo: String = "Seleccione"
@State var expand = false

var body: some View {

    VStack {
        Text(categoria).fontWeight(.heavy).foregroundColor(.white)
        HStack {
            Text(titulo).fontWeight(.light).foregroundColor(.white)
            Image(systemName: expand ? "chevron.up" : "chevron.down").resizable().frame(width: 10, height: 6).foregroundColor(.white)

        }.onTapGesture {
            self.expand.toggle()
        }

        if expand {
            ScrollView(showsIndicators: true) {
                ForEach(0..<self.datos.count){ nombre in
                    Button(action: {
                        print(self.datos[nombre])
                        self.titulo = self.datos[nombre]
                        self.expand.toggle()
                        diccionarioDatos[self.categoria] = self.titulo
                        print(diccionarioDatos)
                    }) {
                        Text(self.datos[nombre]).foregroundColor(.white)
                    }
                }
            }
            .frame(maxHeight: 150)
            .fixedSize()
        }
    }
    .padding()
    .background(LinearGradient(gradient: .init(colors: [.blue, .green]), startPoint: .top, endPoint: .bottom))
    .cornerRadius(20)
    .animation(.spring())
}
Run Code Online (Sandbox Code Playgroud)

}

我点击了“Modelo”下的“2018”,出于某种原因选择了“2015”

这是下拉菜单的样子

Asp*_*eri 5

当我测试时,观察到的行为是由于可动画属性的顺序。在您的情况下,将圆角移入背景本身就可以解决问题。

所以代替

.background(
    LinearGradient(gradient: .init(colors: [.blue, .green]), startPoint: .top, endPoint: .bottom)
)
.cornerRadius(20)
Run Code Online (Sandbox Code Playgroud)

.background(
    LinearGradient(gradient: .init(colors: [.blue, .green]), startPoint: .top, endPoint: .bottom)
        .cornerRadius(20)
)
Run Code Online (Sandbox Code Playgroud)