I would like to have a button, which when pressed, changes to 'confirm'. On the second press, it executes the action. Simple enough so far.
I would also like that whenever the 'confirm' version of the button is showing, any interaction with any other view would reset the button to its original state. That could be touching the background, pressing another button, going to another tab, etc.
My attempt is something like:
struct ContentView: View {
@State private var confirmShowing = false
var body: some View {
ZStack {
// Tappable background just to remove the confirmation
Color(.systemBackground)
.edgesIgnoringSafeArea(.all)
.onTapGesture {
withAnimation {
confirmShowing = false
}
}
VStack {
// Button which needs confirmation
Button(action: {
if confirmShowing {
print("Executing")
}
withAnimation {
confirmShowing.toggle()
}
}) {
Text( confirmShowing ? "Confirm" : "Do something" )
}
.padding()
.background( Rectangle().foregroundColor( Color(.secondarySystemBackground) ) )
.padding()
// Completely different button which also should first reset confirmation
Button("Do something else") {
withAnimation {
confirmShowing = false
}
// do some other stuff
}
.padding()
.background( Rectangle().foregroundColor( Color(.secondarySystemBackground) ) )
.padding()
}
}
}
}
It works for this very simple example, but it's not scalable. If I have 50 views I would have to add something to each of them just to control this one button.
Is there a better way? I'm happy to use UIViewRepresentable/UIViewControllerRepresentable.
UIKit must have this functionality right? I see it all the time in other apps and iOS in general.