How to create custom ButtonStyles in SwiftUI | Advanced Learning #2
ButtonStyle
프로토콜을 사용, 커스텀 버튼 스타일 구현ButtonStyle
프로토콜을 준수하는 버튼 스타일 구조체 구현extension
상 버튼 스타일을 구현, 리턴하는 함수 구현import SwiftUI
struct PressableButtonStyle: ButtonStyle {
let scaledAmount: CGFloat
init(scaledAmount: CGFloat = 0.9) {
self.scaledAmount = scaledAmount
}
func makeBody(configuration: Configuration) -> some View {
configuration.label
.scaleEffect(configuration.isPressed ? scaledAmount : 1.0)
// .brightness(configuration.isPressed ? 0.1 : 0)
.opacity(configuration.isPressed ? 0.9 : 1.0)
}
}
extension View {
func withPressableStyle(_ scaledAmount: CGFloat = 0.9) -> some View {
buttonStyle(PressableButtonStyle(scaledAmount: scaledAmount))
}
}
configuration
을 통해 버튼을 '눌렀을 때' (isPressed
) 어떤 모습이 될지 설정할 수 있다. opacity
, scaleEffect
, brightness
등 다양한 라벨 이펙트를 줄 수 있다.import SwiftUI
struct PressableButtonStyle: ButtonStyle {
let scaledAmount: CGFloat
init(scaledAmount: CGFloat = 0.9) {
self.scaledAmount = scaledAmount
}
func makeBody(configuration: Configuration) -> some View {
configuration.label
.scaleEffect(configuration.isPressed ? scaledAmount : 1.0)
// .brightness(configuration.isPressed ? 0.1 : 0)
.opacity(configuration.isPressed ? 0.9 : 1.0)
}
}
extension View {
func withPressableStyle(_ scaledAmount: CGFloat = 0.9) -> some View {
buttonStyle(PressableButtonStyle(scaledAmount: scaledAmount))
}
}
struct ButtonStyleBootCamp: View {
var body: some View {
VStack {
Button(action: {
}, label: {
Text("CLICK ME")
.font(.headline)
.foregroundColor(.white)
.frame(height: 55)
.frame(maxWidth: .infinity)
.background(.blue)
.cornerRadius(10)
.shadow(color: Color.blue.opacity(0.3), radius: 10, x: 0.0, y: 10)
})
.buttonStyle(PressableButtonStyle())
Button(action: {
}, label: {
Text("CLICK ME")
.font(.headline)
.foregroundColor(.white)
.frame(height: 55)
.frame(maxWidth: .infinity)
.background(.blue)
.cornerRadius(10)
.shadow(color: Color.blue.opacity(0.3), radius: 10, x: 0.0, y: 10)
})
.buttonStyle(PressableButtonStyle(scaledAmount: 0.7))
Button(action: {
}, label: {
Text("CLICK ME")
.withDefaultButtonFormmating(.red)
})
.withPressableStyle(0.5)
}
.padding(40)
}
}