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)
}
}
SwiftUI ⟩
View ⟩ Appearance Modifiers ⟩
.controlSize(_:) - size for controls within this view.
Controls ⟩ Button ⟩
.buttonBorderShape(_:) - border shape.
ButtonStyle (protocol) - standard button interaction behavior.
ButtonBorderShape (struct)
ButtonRole (struct) - purpose of a button.
PrimitiveButtonStyle (protocol) - custom interaction behavior & appearance.
.automatic, .bordered, .borderedProminent, .borderless, .plain
.card (tvOS 14), .link (macOS 10.15)
Last updated
Was this helpful?