djk3000 / ME

4 stars 2 forks source link

SwiftUI-ViewModifier #78

Open djk3000 opened 2 years ago

djk3000 commented 2 years ago

ViewModifier: Conform to the ViewModifier protocol when you want to create a reusable modifier that you can apply to any view. 这个之前没发现,后来看了一下发现就是一个style,可以用来统一的样式,这样就可以多个地方进行使用 看一下例子:

//这里等于就是写了一个border的style,可以在任何View上套用
struct BorderedCaption: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.caption2)
            .padding(10)
            .overlay(
                RoundedRectangle(cornerRadius: 15)
                    .stroke(lineWidth: 1)
            )
            .foregroundColor(Color.blue)
    }
}

struct ExampleView: View {
    var body: some View {
        VStack {
            Text("Text without blue border")
             //使用
            Text("Text with blue border")
                .modifier(BorderedCaption())
        }
    }
}

平时使用的时候更加常用的是在extension里面进行包含进去,还可以进行内容的传递:

struct NewTextStyle: ViewModifier{
    var text: String

    func body(content: Content) -> some View {
        VStack{
            Image(systemName: "bus")
                        .resizable()
                        .frame(width:50, height:50)

            content
                .font(.caption)
                .foregroundColor(.white)
                .padding(5)
                .background(.black)

            Text(text)
        }
    }
}

extension Text{
    func stackText(text:String) -> some View{
        modifier(NewTextStyle(text: text))
    }
}

//使用
Text("Hello World!")
       .stackText(text: "bus")
图片