Delete a Button after it is pressed in SwiftUI
In this tutorial, we will see how we can delete a button after it is pressed in SwiftUI. In most apps, when we press a button in an app’s user interface, it typically remains visible to trigger actions or transitions. However, in rare cases, removing a button after it has been pressed may be necessary. This could be useful for game mechanics, one-time actions, or transitory user interface elements.
Now, have a look at the steps below
Define the initial state
First of all, we have to define a boolean variable with an initial state to indicate whether the button should be displayed or not.
@State private var showButton = true
In the above code, I have declared a private state variable which is showButton
with an initial value of true
.
The private
modifier keeps a variable accessible only within the specific part of the program where it’s declared, which means it cannot be accessed or modified from outside the view.
Create the main body of the view
Now, inside the body
property of the ContentView
struct, we have to set up the main layout of your view, which will contain the button. Just replace the existing code with the code mentioned below.
VStack { if(showButton == true) { Button("Press the Button to Hide") { self.showButton = false } } }
In the above program, I have used a conditional statement to check the value of showButton
. If it’s true
, the button will be displayed, otherwise, it won’t be shown.
Then, the code self.showButton = false
will hide the button and it will no longer be shown because the button is conditionally rendered based on the boolean value of showButton
.
Now, have a look at the complete code below
import SwiftUI struct ContentView: View { @State private var showButton = true var body: some View { VStack { if(showButton == true) { Button("Press the Button to Hide") { self.showButton = false } } } } }
When we tap the button, the code self.showButton = false
will execute. This will change the value of showButton from true to false.
Since the showButton
is now false, the condition in the if statement (if showButton == true
) becomes false, and the button will no longer be included in the view.
Output:
Leave a Reply