SwiftUI 自定义组件样式

阴影

1
2
3
4
5
6
7
8
9
10
11
struct TestView:View {
var body: some View {
VStack() {
Text("Hello")
Text("World")
}
.padding()
.background(Color.cyan)
.shadow(color: Color.black, radius: 10, x: 0, y: 0)
}
}

可以发现 hello world 也存在阴影。代码需要调整为:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct TestView:View {
var body: some View {
VStack() {
Text("Hello")
Text("World")
}
.padding()
.background(
Color.cyan
.shadow(color: Color.black, radius: 10, x: 0, y: 0)
)
}
}

问题解决。

圆角

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct TestView:View {
var body: some View {
VStack() {
Text("Hello")
Text("World")
}
.padding()
.background(
Color.cyan
.cornerRadius(12)
// .clipShape(.rect(cornerRadius: 12)),胶囊 .clipShape(.capsule)
.shadow(color: Color.black, radius: 10, x: 0, y: 0)
)
}
}

使用 .clipShape(.rect(cornerRadius: 12)) 也可以绘制圆角,使用 .clipShape(.capsule) 则是绘制胶囊图形。

另外也可以:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct TestView:View {
var body: some View {
VStack() {
Text("Hello")
Text("World")
}
.padding()
.background(Color.cyan)
.cornerRadius(12)
// .clipShape(.rect(cornerRadius: 12)),胶囊 .clipShape(.capsule)
.shadow(color: Color.black, radius: 10, x: 0, y: 0)
}
}

自定义圆角的位置

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
struct TestView:View {
var body: some View {
VStack() {
Text("Hello")
Text("World")
}
.padding()
.background(
RoundedCorners(color: .cyan, tl: 0, tr: 12, bl: 12, br: 0)
.shadow(color: Color.black, radius: 10, x: 0, y: 0)
)
//.shadow(color: Color.black, radius: 10, x: 0, y: 0) .shadow 在这里使用的话阴影显示会有问题,hello world 也会带阴影
}
}

struct RoundedCorners: View {
var color: Color = .blue
var tl: CGFloat = 0.0
var tr: CGFloat = 0.0
var bl: CGFloat = 0.0
var br: CGFloat = 0.0

var body: some View {
GeometryReader { geometry in
Path { path in

let w = geometry.size.width
let h = geometry.size.height

// Make sure we do not exceed the size of the rectangle
let tr = min(min(self.tr, h/2), w/2)
let tl = min(min(self.tl, h/2), w/2)
let bl = min(min(self.bl, h/2), w/2)
let br = min(min(self.br, h/2), w/2)

path.move(to: CGPoint(x: w / 2.0, y: 0))
path.addLine(to: CGPoint(x: w - tr, y: 0))
path.addArc(center: CGPoint(x: w - tr, y: tr), radius: tr, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
path.addLine(to: CGPoint(x: w, y: h - br))
path.addArc(center: CGPoint(x: w - br, y: h - br), radius: br, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 90), clockwise: false)
path.addLine(to: CGPoint(x: bl, y: h))
path.addArc(center: CGPoint(x: bl, y: h - bl), radius: bl, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false)
path.addLine(to: CGPoint(x: 0, y: tl))
path.addArc(center: CGPoint(x: tl, y: tl), radius: tl, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false)
}
.fill(self.color)
}
}
}


SwiftUI 自定义组件样式
https://wonderhoi.com/2024/11/28/SwiftUI-自定义组件样式/
作者
wonderhoi
发布于
2024年11月28日
许可协议