# 2.4.2 控件-链接


<br>


# [Link](https://developer.apple.com/documentation/swiftui/link)

Link 可以打开网页链接，如果通用链接（Universal Link）支持，会跳转到对应的 App 页面。

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

# [ShareLink](https://developer.apple.com/documentation/swiftui/sharelink)

ShareLink 用于生成分享链接，点击时会弹出分享视图。凡是遵循 [Transferable](https://developer.apple.com/documentation/coretransferable/transferable) 协议的内容都可以被分享，Swift 中的如下数据类型已实现该协议：

- String
- Data
- URL
- Attributed String
- Image

以分享 URL 为例：

```swift
private let appleURL: URL = .init(string: "https://apple.com")!

ShareLink(item: appleURL)
```

ShareLink 默认会生成一个带分享图标和标题的链接，我们也可以自定义分享链接视图：

```swift
ShareLink(
  item: appleURL,
  subject: Text("I'm a subject"),
  message: Text("I'm a message")) {
    Label("apple", systemImage: "applelogo")
      .foregroundColor(.red)
  }
```

`subject` 和 `message` 是可选参数，是否显示取决于分享的类型。比如分享至提醒事项时，message 会作为新建提醒的标题，分享至邮件时，subject 会作为邮件标题。

假设有如下数据模型：

```swift
fileprivate struct Person: Codable {
  var name: String
  var avatar: String
}
```

现在需要分享 Person 类型的数据，可能为用户名、头像或者其它更为复杂的数据。这里以分享用户头像为例，首先需要为 Person 实现 Transferable 协议：

```swift
extension Person: Transferable {
  static var transferRepresentation: some TransferRepresentation {
    ProxyRepresentation(exporting: \.image)
  }
  
  var image: Image {
    .init(avatar)
  }
}
```

Transferable 协议只有一个必须实现的静态属性 `transferRepresentation`，它是不透明类型 `some TransferRepresentation`。SwiftUI 内置了几种已经实现 TransferRepresentation 协议的类型，比如 CodableRepresentation、DataRepresentation、FileRepresentation 以及 ProxyRepresentation 等。

[ProxyRepresentation](https://developer.apple.com/documentation/coretransferable/proxyrepresentation) 有点特别，它可以将已经实现 Transferable 协议的类型为己所用，作用有点类似代理，所以命名上也很形象。比如上面代码中的 image 是已经实现 Transferable 协议的 Image 类型，我们只需要使用 ProxyRepresentation 包装一下即可。

然后就可以使用 ShareLink 进行分享了：

```swift
private let person = Person(
  name: "zzzwco",
  avatar: "parrot_small"
)

ShareLink(
  item: person,
  preview: SharePreview(
    person.name,
    image: person.image
  )
)
```




---

> 作者: 宋明  
> URL: https://apolla.cc/posts/swiftui-eul/2.4.2-%E6%8E%A7%E4%BB%B6-%E9%93%BE%E6%8E%A5/  

