๐Ÿ”ฐButton Styles

SwiftUI โŸฉ Controls โŸฉ Button โŸฉ Styles

๐Ÿ“— ๅƒ่€ƒ๏ผšSundell โŸฉ Encapsulating SwiftUI view styles

// โญ๏ธ 1. custom button style
struct PrimaryButtonStyle: ButtonStyle {
    // โญ๏ธ protocol requirement: makeBody()
    func makeBody(configuration: Configuration) -> some View {
        // โญ๏ธ button label
        configuration.label
            .foregroundColor(.white)
            .font(.body.bold())
            .padding(10)
            .padding(.horizontal, 20)
            .background(.blue)
            // โญ๏ธ button state
            .opacity(configuration.isPressed ? 0.5 : 1)
            .cornerRadius(10)
    }
}

// โญ๏ธ 2. convenience extension
private extension ButtonStyle where Self == PrimaryButtonStyle {
    // โญ๏ธ ButtonStyle.primary
    static var primary: Self { .init() }
}

// custom view
struct LoginView: View {
    
    @State private var username = ""
    @State private var password = ""
    
    var body: some View {
        VStack(spacing: 15) {
            TextField("Username", text: $username)
            SecureField("Password", text: $password)
            Button("Log in") {}
        }
        .textFieldStyle(.roundedBorder)
        // โญ๏ธ 3. apply custom button style
        .buttonStyle(.primary)
    }
}

Last updated