viewModifier相当前段中的css,定义一种样式,其他地方都可以使用
只需要实现viewModifier
协议就可以嘞
struct myModifier: ViewModifier {
// opaque return types
func body(content: Content) -> some View {
}
}
some --- 用在当返回值为不确定类型的情况。
struct myModifier: ViewModifier {
// opaque return types
func body(content: Content) -> some View {
content.foregroundColor(.red).font(Font.system(size: 20,weight: .bold)).border(.green, width: 2)
}
}
struct ViewModifierDemo: View {
var body: some View {
VStack{
Text("Hello, World!").modifier(myModifier())
Text("hhh").modifier(myModifier())
}
}
}
仿写redacted
public enum RedactionReason {
case placeh
case black
case blurred
}
struct Placeholder: ViewModifier{
func body(content: Content) -> some View {
content
.opacity(0)
.overlay {
RoundedRectangle(cornerRadius: 2).fill(.black.opacity(0.16))
.padding(20)
}
}
}
struct Confidential: ViewModifier{
func body(content: Content) -> some View {
content
.opacity(0)
.overlay {
Color.black
}
}
}
struct Blurred: ViewModifier{
func body(content: Content) -> some View {
content
.blur(radius: 4)
}
}
struct Redactable: ViewModifier {
let reason : RedactionReason?
@ViewBuilder
func body(content: Content) -> some View {
switch reason {
case .placeh:
content
.modifier(Placeholder())
case .black:
content
.modifier(Confidential())
case .blurred:
content
.modifier(Blurred())
case nil:
content
}
}
}
extension View {
func redacted(reason: RedactionReason?) -> some View {
self.modifier(Redactable(reason: reason))
}
}
struct RedactedDemo: View {
var body: some View {
Text("Hello, World!")
.padding()
// .modifier(Placeholder())
.redacted(reason: .placeh)
}
}