I have switched from developing an app from Obj-C to swiftUI. I have a button, when clicked on it should show popupview. Followed this link to display popup https://blog.techchee.com/how-to-create-a-pop-up-view-with-swiftui/
But popup doesn't show up when clicked on the button. Here's my code
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 )
}
}
Plz help in where am going wrong?
As per your design, you can just add conditions within the main ZStack and hide show the view. Also, you can use the sheet.
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 )
}
}