美文网首页
swiftUI-viewModifier

swiftUI-viewModifier

作者: Mjs | 来源:发表于2023-04-24 20:26 被阅读0次

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

    相关文章

      网友评论

          本文标题:swiftUI-viewModifier

          本文链接:https://www.haomeiwen.com/subject/csxpjdtx.html