Create toggle switch in SwiftUI
In this tutorial, we will learn how to create toggle switch in SwiftUI.
Basically, toggle lets a user switch between true and false states. It is commonly used to represent options with a simple on/off or true/false state.
Creating Toggle Switches in SwiftUI
The Toggle control makes it simple to display some text on the app screen when a toggle switch is turned on and hide it when it is turned off.
Now, have a look at the example below
import SwiftUI struct ContentView: View { @State var myText: Bool = false var body: some View { VStack (spacing: 40) { Toggle(isOn: $myText){ Text("Click the button") } if myText { Text("Welcome to CodeSpeedy") } } .padding() } }
In the above program, I have used the @State
property wrapper to create a state variable myText
, which is initialized to false. The @State
property wrapper allows SwiftUI to automatically update the view whenever the state changes.
After that, I have created a vertical stack (VStack) of views, with a spacing of 40 points between them. The spacing is the vertical distance between the elements inside the stack.
After that, I have created a toggle switch with a text label and bound the isOn
parameter to the myText
state variable using the $
prefix. So, whenever the toggle is changed, the myText
state variable will be updated accordingly.
Then, I have used a conditional block to display the “Welcome to CodeSpeedy” text only if the myText
state variable is true.
Output:
Fixing Dynamic View Height with frame() modifier
As you can see in the above GIF output, when we are pressing the toggle button, the text is automatically uplifting. To solve the issue we can fix the height of the stack view by creating a frame like below.
import SwiftUI struct ContentView: View { @State var myText: Bool = false var body: some View { VStack (spacing: 40) { Toggle(isOn: $myText) { Text("Click the button") } VStack{ if myText { Text("Welcome to CodeSpeedy") } } //To fix the height of the stack view .frame(maxHeight: 100 ) } .padding() } }
In the above program, I used .frame()
to fix the height of the stack view. We can set the dimensions and the alignment with this modifier.
Output:
As you can see in the above output, the issue has been fixed. We can fix the height of our stack view according to the length of our text.
Leave a Reply