在SwiftUI中点击按钮时调用函数



我已经从开发应用程序Obj-C切换到swiftUI。我有一个按钮,当点击它应该显示popupview。点击此链接显示弹出窗口https://blog.techchee.com/how-to-create-a-pop-up-view-with-swiftui/

但是点击按钮时弹出窗口不显示。这是我的代码

struct Location: View {
var body: some View {
ZStack{
Button(action: {
popUpView()

}, label: {
Text("Select Location")
.frame(minWidth: 0, maxWidth: 500)
.padding()
.background(Color.clear)
.foregroundColor(Color.black)
.font(.custom("Open Sans", size: 18))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray, lineWidth: 2)
)
})


}
}
private let choices = ["Apple", "Orange", "Papaya", "Grape", "Star Fruit", "Strawberries", "Raspberries", "Blueberries"].sorted()

func popUpView()-> some View  {


VStack (spacing : 10) {
Text("Choices Of Fruits").font(Font.custom("Avenir-Black", size: 18.0))
.position(x:100 , y:400)
List(choices, id:.self) { Text($0) }
Button(action: {
withAnimation {
}
}, label: {
Text("Close")
})

}
.padding()
.frame(width: 240, height: 300)
.background(Color.white)
.cornerRadius(20)
.shadow(radius: 20 )
}

}

请帮助在哪里我错了?

根据您的设计,您可以在主ZStack中添加条件并隐藏显示视图。此外,您还可以使用表单。

struct Location: View {
@State private var isPresent: Bool = false // <-- Here
var body: some View {
ZStack{
Button(action: {
withAnimation {
isPresent = true // <-- Here
}

}, label: {
Text("Select Location")
.frame(minWidth: 0, maxWidth: 500)
.padding()
.background(Color.clear)
.foregroundColor(Color.black)
.font(.custom("Open Sans", size: 18))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.gray, lineWidth: 2)
)
})

if isPresent { // <-- Here
popUpView()
}
}
}

private let choices = ["Apple", "Orange", "Papaya", "Grape", "Star Fruit", "Strawberries", "Raspberries", "Blueberries"].sorted()


func popUpView()-> some View  {


VStack (spacing : 10) {
Text("Choices Of Fruits").font(Font.custom("Avenir-Black", size: 18.0))
.position(x:100 , y:400)
List(choices, id:.self) { Text($0) }
Button(action: {
withAnimation {
isPresent = false // <-- Here
}
}, label: {
Text("Close")
})

}
.padding()
.frame(width: 240, height: 300)
.background(Color.white)
.cornerRadius(20)
.shadow(radius: 20 )

}

}

相关内容

  • 没有找到相关文章

最新更新