ๆณจๆ๏ผๆฌไพไฝฟ็จๅ
ฉ็จฎไธๅๆนๆณไพๆงๅถ Button ็ๅค่งใ
็ฑๆผ btn1 ๆฏ็ฑ State ่ฎๆธไพใๅๆใisPressed ็็ๆ
๏ผๆไปฅๅช่ฆๆไธไธ btn1๏ผๆ้ๅฐฑๆ้ทไธๅป๏ผ่ไธไธๆๅฝๅไพใbtn2 ๅ็ฑ configuration.isPressed ่ชๅ็ฃๆง๏ผๆไปฅๅชๆๆ็บๆไฝ๏ผๆๆไฟๆใๆไธ็็ๆ
ใใ
โฌ๏ธ ้่ฆ๏ผ .neumorphic() (modifier)
struct ContentView: View {
@State private var isPressed: Bool = false
let color = Color(white: 0.9)
var body: some View {
HStack {
VStack(alignment: .trailing, spacing: 40) {
btn1 // โญ๏ธ 1. use view modifier
btn2 // โญ๏ธ 2. use custom button style
}
.offset(x: -80)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(color)
}
var btn1: some View {
Button{
self.isPressed.toggle()
} label: {
Label("Hello", systemImage: "person")
// โญ๏ธ 1. view modifier
.neumorphic(isPressed: $isPressed, color: color)
}
.background(color)
.overlay {
Text("้ปไธไธๅฐฑๆไธๆฒ")
.foregroundColor(.gray)
.offset(x: 150)
}
}
var btn2: some View {
Button{} label: {
Label("World", systemImage: "globe")
}
// โญ๏ธ 2. custom button style
.buttonStyle(.neumorphic(color: color)) // ๐ .neumorphic()
.overlay {
Text("่ฆๆไฝๆๆไธๆฒ")
.foregroundColor(.gray)
.offset(x: 150)
}
}
}
import SwiftUI
public struct NeumorphicButtonStyle: ButtonStyle {
var color: Color
// โญ protocol's only requirement
public func makeBody(configuration: Self.Configuration) -> some View {
// โญ `configuration` contains:
// - .label : content of the button (View)
// - .isPressed: state of the button (Bool)
let isPressed = configuration.isPressed
let s: CGFloat = isPressed ? 5: 15 // positive shadow offset
let r: CGFloat = isPressed ? 7: 10 // shadow radius
let k: CGFloat = isPressed ? 0.95 : 1 // scale
configuration.label
.foregroundColor(.black)
.padding(20)
.background(
ZStack {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.shadow(color: .white, radius: r, x: -s, y: -s)
.shadow(color: .black, radius: r, x: s, y: s)
.blendMode(.overlay)
RoundedRectangle(cornerRadius: 10, style: .continuous)
.fill(color)
}
)
.scaleEffect(k)
.foregroundColor(.primary)
.animation(.spring())
}
}
// ๐ .neumorphic(color:)
// โญโโโโโโโโโ โญ๏ธ important โโโโโโโโโโโฎ
extension ButtonStyle where Self == NeumorphicButtonStyle {
public static func neumorphic(color: Color) -> some ButtonStyle {
NeumorphicButtonStyle(color: color)
}
}
SwiftUI โฉ Controls โฉ Button โฉ
ButtonStyle (protocol) - standard button interaction behavior.
PrimitiveButtonStyle (protocol) - custom interaction behavior & appearance.
.automatic, .bordered, .borderedProminent, .borderless, .plain
.card (tvOS 14), .link (macOS 10.15)