# 2.1.2 文本-Label


<br>


# 构建方法

[Label](https://developer.apple.com/documentation/swiftui/label) 可以快速生成图片和文字的组合，默认布局是左图右文。

图片可以是资源文件：

```swift
Label("Eul", image: "icon")
```

也可以是 [SF Symbols](https://developer.apple.com/sf-symbols/) 中的图片：

```swift
Label("Swift", systemImage: "swift")
```

在 Xcode 中快速唤出 SF Symbols 面板可使用快捷键：⌘ + ⇧ + L。

使用系统内置图标时，默认的图标颜色是工程配置的 AccentColor。

Label 可以自定义 title 和 icon：

```swift
Label {
  Text("iPhone Plus")
    .foregroundStyle(.linearGradient(
      .init(colors: [.blue, .purple]),
      startPoint: .topLeading, endPoint: .bottomTrailing)
    )
    .bold()
} icon: {
  Image(systemName: "iphone")
    .font(.title)
    .foregroundStyle(.purple)
}
```

<span style="background: #007BFF; color: white; padding: 3px 10px; border-radius: 5px">> 查看示例</span>

# 设置 LabelStyle

系统内置了如下 [LabelStyle](https://developer.apple.com/documentation/swiftui/labelstyle)：

- automatic
- titleAndIcon
- titleOnly
- iconOnly

样式效果见示例。

# 自定义样式

自定义 Label 样式需要实现 LabelStyle 协议，如下是一个具有渐变色和阴影效果的自定义样式，而且将 Label 默认的布局改成了上图下文：

```swift
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，然后对其进行自定义。




---

> 作者: 宋明  
> URL: https://apolla.cc/posts/2.1.2-%E6%96%87%E6%9C%AC-label/  

