构建方法
Label 可以快速生成图片和文字的组合,默认布局是左图右文。
图片可以是资源文件:
1
|
Label("Eul", image: "icon")
|
也可以是 SF Symbols 中的图片:
1
|
Label("Swift", systemImage: "swift")
|
在 Xcode 中快速唤出 SF Symbols 面板可使用快捷键:⌘ + ⇧ + L。
使用系统内置图标时,默认的图标颜色是工程配置的 AccentColor。
Label 可以自定义 title 和 icon:
1
2
3
4
5
6
7
8
9
10
11
12
|
Label {
Text("iPhone Plus")
.foregroundStyle(.linearGradient(
.init(colors: [.blue, .purple]),
startPoint: .topLeading, endPoint: .bottomTrailing)
)
.bold()
} icon: {
Image(systemName: "iphone")
.font(.title)
.foregroundStyle(.purple)
}
|
> 查看示例
设置 LabelStyle
系统内置了如下 LabelStyle:
- automatic
- titleAndIcon
- titleOnly
- iconOnly
样式效果见示例。
自定义样式
自定义 Label 样式需要实现 LabelStyle 协议,如下是一个具有渐变色和阴影效果的自定义样式,而且将 Label 默认的布局改成了上图下文:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
fileprivate struct MyStyle: LabelStyle {
let spacing: CGFloat
func makeBody(configuration: Configuration) -> some View {
VStack(spacing: spacing) {
configuration.icon
configuration.title
}
.font(.title3)
.bold()
.shadow(color: .blue, radius: 2)
.foregroundStyle(.linearGradient(
.init(colors: [.red, .orange, .blue, .purple]),
startPoint: .topLeading, endPoint: .bottomTrailing))
}
}
fileprivate extension LabelStyle where Self == MyStyle {
static func myStyle(spacing: CGFloat) -> Self {
.init(spacing: spacing)
}
}
|
Configuration 类型为 LabelStyleConfiguration,它是一个结构体,我们可以从中获取 Label 的 Icon 和 Title,然后对其进行自定义。