Learn how to create buttons and handle user interactions.
The Button view allows users to trigger actions.
Button(action: {
print("Button tapped!")
}) {
Text("Tap Me")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
Explanation:
action: The code to execute when the button is tapped.Text view with modifiers to style the button..padding(): Adds padding around the text..background(Color.blue): Sets the background color of the button to blue..foregroundColor(.white): Sets the text color to white..cornerRadius(10): Rounds the corners of the button with a radius of 10 points.Buttons can be customized with different styles and views.
Button(action: {
print("Custom Button tapped!")
}) {
HStack {
Image(systemName: "star.fill")
Text("Favorite")
}
.padding()
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(10)
}
Explanation:
HStack: A horizontal stack that arranges its children horizontally.Image(systemName: "star.fill"): Displays a system image with the name "star.fill".Text("Favorite"): Displays a text view with the string "Favorite"..padding(): Adds padding around the horizontal stack..background(Color.green): Sets the background color of the button to green..foregroundColor(.white): Sets the text and image color to white..cornerRadius(10): Rounds the corners of the button with a radius of 10 points.Displaying action sheets and alerts to provide additional information or options to the user.
@State private var showAlert = false
var body: some View {
Button("Show Alert") {
showAlert = true
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Alert"), message: Text("This is an alert"), dismissButton: .default(Text("OK")))
}
}
Explanation:
@State private var showAlert = false: Declares a state variable to control the alert's visibility.Button changes showAlert to true when tapped, triggering the alert to appear.alert modifier shows an alert when showAlert is true.Alert(title: Text("Alert"), message: Text("This is an alert"), dismissButton: .default(Text("OK"))): Defines the alert's title, message, and dismiss button.Using gestures to handle more complex interactions.
Text("Tap Me")
.onTapGesture {
print("Text tapped!")
}
Explanation:
onTapGesture: Adds a tap gesture recognizer to the text view.onTapGesture contains the code to execute when the text is tapped.