Post

SwiftUI2:自定义View之将属性组合在一起便捷操作

参考:

由于相似的属性很多,代码显得很长,可以将一些相似的代码全封装起来,代码看起来会间接很多,想要将公共的代码组合在一起

方案一:自定义View

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
struct CapsuleText: View {
    var text: String

    var body: some View {
        Text(text)
            .font(.largeTitle)
            .padding()
            .foregroundColor(.white)
            .background(Color.blue)
            .clipShape(Capsule())
    }
}
struct CapsuleText2: View {
    var text: String

    var body: some View {
        Text(text)
            .font(.largeTitle)
            .padding()
            .background(Color.blue)
            .clipShape(Capsule())
    }
}
// 调用Demo
VStack(spacing: 10) {
        CapsuleText(text: "First")
        CapsuleText(text: "Second")
        CapsuleText2(text: "Third")
                .foregroundColor(.white)
            CapsuleText2(text: "Fouth")
                .foregroundColor(.yellow)
    }

方案二:使用Modifier

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// MARK: - 使用Modifier进行组合
struct MyCapsule: ViewModifier {
    var foregroundColor: Color
    func body(content: Content) -> some View {
        content
            .font(.largeTitle)
            .padding()
            .foregroundColor(foregroundColor)
            .background(Color.blue)
            .clipShape(Capsule())
    }
}

extension View {
    func myCapsuleStyle(_ foregroundColor: Color = .white) -> some View {
        self.modifier(MyCapsule(foregroundColor: foregroundColor))
    }
}
// 调用Demo
VStack(spacing: 10) {
        Text("First1").myCapsuleStyle()
        Text("Second1").myCapsuleStyle()
        Text("Third1").myCapsuleStyle(.red)
        Text("Fouth1").myCapsuleStyle(.green)
    }

image

This post is licensed under CC BY 4.0 by the author.