1. ViewModifier 视图修饰符
1.1 创建默认按钮视图修饰符 ViewModifierBootcamp.swift
Swift
import SwiftUI
/// 默认按钮修饰符
struct DefaultButtonViewModifier: ViewModifier{
let bcakgroundColor: Color
func body(content: Content) -> some View {
content
.foregroundColor(.white)
.frame(height: 55)
.frame(maxWidth: .infinity)
.background(bcakgroundColor)
.cornerRadius(10)
.shadow(radius: 10)
}
}
// 扩展 View
extension View {
func withDefaultButtonFormatting(backgroundColor: Color = .blue) -> some View{
modifier(DefaultButtonViewModifier(bcakgroundColor: backgroundColor))
}
}
/// 视图修饰符
struct ViewModifierBootcamp: View {
var body: some View {
VStack(spacing: 10) {
Text("Hello,world!")
.font(.headline)
.withDefaultButtonFormatting(backgroundColor: .orange)
Text("Hello,everyone!")
.font(.subheadline)
.withDefaultButtonFormatting()
Text("Hello !!!")
.font(.title)
.withDefaultButtonFormatting(backgroundColor: .red)
}
.padding()
}
}
struct ViewModifierBootcamp_Previews: PreviewProvider {
static var previews: some View {
ViewModifierBootcamp()
}
}
1.2 效果图:
2. ButtonStyle 自定义按钮样式
2.1 创建按下按钮样式,ButtonStyleBootcamp.swift
Swift
import SwiftUI
/// 按下按钮样式
struct PressableButtonStyle: ButtonStyle{
let scaledAmount: CGFloat
init(scaledAmount: CGFloat) {
self.scaledAmount = scaledAmount
}
func makeBody(configuration: Configuration) -> some View {
configuration.label
// 缩放
.scaleEffect(configuration.isPressed ? scaledAmount : 1.0)
// 点亮度
//.brightness(configuration.isPressed ? 0.05 : 0)
.opacity(configuration.isPressed ? 0.86 : 1)
}
}
/// 扩展 View
extension View{
/// 按钮的样式
func withPressableStyle(scaledAmount: CGFloat = 0.9) -> some View{
buttonStyle(PressableButtonStyle(scaledAmount: scaledAmount))
}
}
/// 按钮样式
struct ButtonStyleBootcamp: View {
var body: some View {
Button {
} label: {
Text("Click Me")
.font(.headline)
.withDefaultButtonFormatting()
}
.withPressableStyle(scaledAmount: 0.86)
.padding(40)
}
}
struct ButtonStyleBootcamp_Previews: PreviewProvider {
static var previews: some View {
ButtonStyleBootcamp()
}
}