//
// ContentView.swift
// Buttons
//
// Created by WilliamJiamin on 2024/6/20.
//
//
//You can check more on Button at
//https://developer.apple.com/documentation/swiftui/button
import SwiftUI
struct ContentView: View {
@State private var message: String = "Welcome! Press a button below."
var body: some View {
VStack {
Spacer()
Text(message)
.font(.headline)
.foregroundColor(.blue)
.padding()
.frame(maxWidth: .infinity)
.background(Color(.systemGray6))
.cornerRadius(10)
.padding(.horizontal)
VStack(spacing: 20) {
Button("Default Button") {
message = "You pressed the Default Button!"
}
.buttonStyle(PrimaryButtonStyle())
Button("Destructive Button", role: .destructive) {
message = "You pressed the Destructive Button!"
}
.buttonStyle(DestructiveButtonStyle())
Button("Cancel Button", role: .cancel) {
message = "You pressed the Cancel Button!"
}
.buttonStyle(CancelButtonStyle())
Button("Custom Button") {
message = "You pressed the Custom Button!"
}
.buttonStyle(CustomButtonStyle())
}
.frame(maxWidth: .infinity)
.padding()
Spacer()
}
}
}
// Primary button style
struct PrimaryButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.padding()
.background(configuration.isPressed ? Color.blue.opacity(0.5) : Color.blue)
.cornerRadius(8)
.scaleEffect(configuration.isPressed ? 0.95 : 1.0)
.animation(.easeOut, value: configuration.isPressed)
}
}
// Destructive button style
struct DestructiveButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.padding()
.background(configuration.isPressed ? Color.red.opacity(0.5) : Color.red)
.cornerRadius(8)
.scaleEffect(configuration.isPressed ? 0.95 : 1.0)
.animation(.easeOut, value: configuration.isPressed)
}
}
// Cancel button style
struct CancelButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.padding()
.background(Color.gray)
.cornerRadius(8)
.scaleEffect(configuration.isPressed ? 0.95 : 1.0)
.animation(.easeOut, value: configuration.isPressed)
}
}
// Custom button style
struct CustomButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.foregroundColor(.white)
.padding()
.background(Color.green)
.cornerRadius(8)
.scaleEffect(configuration.isPressed ? 0.95 : 1.0)
.animation(.easeOut, value: configuration.isPressed)
}
}
#Preview {
ContentView()
}