SwiftUI LabeledContent 合集

参考:LabeledContent in SwiftUI

下面代码:

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
struct ContentView: View {
var body: some View {
Form {
// Version 1
HStack {
Text("Name")
Spacer()
Text("Samantha Carter")
.foregroundStyle(.secondary)
}

// Version 2
HStack {
Text("Age")
Text(43, format: .number)
.frame(maxWidth: .infinity, alignment: .trailing)
.foregroundStyle(.secondary)
}

// Version 3
HStack {
Text("Home Planet")
Spacer()
Group {
Image(systemName: "globe.europe.africa.fill")
Text("Earth")
}
.foregroundStyle(.secondary)
}

// Version 4
HStack {
VStack(alignment: .leading) {
Text("Team")
Text("SGC")
.font(.callout)
.foregroundStyle(.secondary)
}
Spacer()
Text("SG-1")
.foregroundStyle(.secondary)
}
}
}
}

等效于:

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
struct ContentView: View {
var body: some View {
Form {
Section {
// Version 1: String label & String value
LabeledContent("Name", value: "Samantha Carter")

// Version 2: String label & formatted value
LabeledContent("Age", value: 43, format: .number)

// Version 3: String label & any View as value
LabeledContent("Home Planet") {
Image(systemName: "globe.europe.africa.fill")
Text("Earth")
}

// Version 4: Any View as value & any View as a label
LabeledContent {
Text("SG-1")
} label: {
Text("Team")
Text("SGC")
}
}
}
}
}

另外,LabeledContent 还能这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct ContentView: View {
var body: some View {
Form {
// Version 4: Any View as value & any View as a label
LabeledContent {
Text("Value")
} label: {
Text("Label")
Text("Second Label")
Text("Third Label")
Text("Fourth Label")
// You can add more views, but styling won't change
}
}
}
}

SwiftUI LabeledContent 合集
https://wonderhoi.com/2024/11/29/SwiftUI-LabeledContent-合集/
作者
wonderhoi
发布于
2024年11月29日
许可协议