- 1、设置通用控件配置
//抽象出通用的按钮配置设置
struct CustomViewModifier : ViewModifier {
let background : Color
func body(content: Content) -> some View {
content
.font(.headline)
.foregroundColor(.white)
.frame(maxWidth : .infinity)
.frame(height : 55)
.background(background)
.cornerRadius(30)
.shadow(radius: 10)
.padding()
}
}
- 2、使用例子
// MARK: - VIEW
struct ViewModifierBootCamp: View {
// MARK: - PROPERTY
// MARK: - BODY
var body: some View {
VStack {
Text("Hello")
.modifier(DefaultButtonViewModifier(backgroundColor: .orange))
.font(.headline)
Text("Hello, world")
.withDefaultButtonFormatting(backgroundColor: .green)
.font(.subheadline)
// ViewModifier -> Extention 사용
Text("Hello!!")
.withDefaultButtonFormatting()
.font(.title)
} //: VSTACK
}
}
// MARK: - EXTENTION
extension View {
func withDefaultButtonFormatting(backgroundColor: Color = .blue)-> some View {
modifier(DefaultButtonViewModifier(backgroundColor: backgroundColor))
}
}
-
效果图