swiftUI-viewModifier

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)
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,917评论 2 59
  • 1.1、什么是HTML语义化?有什么好处? 根据内容的结构化(内容语义化),选择合适的标签(代码语义化)便于开发者...
    倾城一梦1123阅读 2,457评论 1 11
  • 1、离职多久了 2、大约多久到岗 3、离这里多远 4、会考虑搬家吗 5、公司会加班 6、为什么要离职 7、你们这个...
    临渊鲸落阅读 1,251评论 0 1
  • JavaScript 1 初识JavaScript 1.1 JavaScript 是什么 JavaScript 是...
    SY阅读 251评论 0 2
  • 学习文章 文集:Hacking with iOS: SwiftUI Edition[https://www.jia...
    xmb阅读 4,543评论 3 14