๐ฐ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