Link
概述
Link 是一个用于导航到指定 URL 的控件。它允许创建一个可点击的元素,当用户点击时会打开指定的 URL。
Link 符合 View 协议,因此可以像使用其他 SwiftUI 视图一样使用它。
1@MainActor @preconcurrency
2struct Link<Label> where Label : View
创建 Link
使用字符串标题
使用 init(_:destination:) 初始化方法创建一个带有字符串标题的 Link:
1/// 使用字符串标题
2Link("访问 Apple 官网", destination: URL(string: "https://www.apple.com")!)
3
4/// 使用 LocalizedStringKey(支持本地化)
5Link("查看服务条款", destination: URL(string: "https://example.com/TOS.html")!)
使用自定义标签
使用 init(destination:label:) 初始化方法创建一个显示自定义标签的 Link:
1/// 使用自定义视图作为标签
2Link(destination: URL(string: "https://www.apple.com")!) {
3 HStack {
4 Image(systemName: "apple.logo")
5 Text("访问 Apple")
6 }
7}
链接行为
默认行为
当用户点击 Link 时,默认行为取决于 URL 的内容类型:
- Universal Link:如果存在关联的 App,则在 App 中打开
- 网页 URL:在用户默认浏览器中打开
- 其他 URL 类型:根据系统配置处理
1// 默认行为示例
2Link("查看文档", destination: URL(string: "https://developer.apple.com/documentation")!)
自定义 URL 处理
可以通过设置 openURL 环境值来覆盖默认行为:
1Link("访问网站", destination: URL(string: "https://www.example.com")!)
2 .environment(\.openURL, OpenURLAction { url in
3 // 自定义处理逻辑
4 print("即将打开: \(url)")
5 return .handled // 标记为已处理,不再执行默认行为
6 })
7
8// 或者使用 .peek() 预览 URL
9Link("访问网站", destination: URL(string: "https://www.example.com")!)
10 .environment(\.openURL, OpenURLAction { url in
11 .peek(url) // 预览 URL,但不执行
12 })
Note
OpenURLAction的返回类型:
.handled- 表示已处理,不会执行系统默认行为.peek(url)- 预览 URL,但允许系统继续处理.discarded- 忽略本次操作
修饰符
buttonStyle
Link 继承自 View,因此可以使用 buttonStyle(_:) 修饰符。SwiftUI 提供了专门的 .link 按钮样式,可以将按钮或容器内的按钮设置为超链接样式:
1/// 应用到单个 Link
2Link("访问网站", destination: URL(string: "https://example.com")!)
3 .buttonStyle(.link)
4
5/// 应用到多个 Link
6VStack {
7 Link("链接 1", destination: URL(string: "https://example.com/1")!)
8 Link("链接 2", destination: URL(string: "https://example.com/2")!)
9}
10.buttonStyle(.link)
Note
.link按钮样式在 macOS 10.15+ 可用
其他修饰符
作为 View,Link 支持所有标准视图修饰符:
1Link("访问网站", destination: URL(string: "https://example.com")!)
2 .foregroundColor(.blue) // 前景色
3 .font(.headline) // 字体
4 .padding() // 内边距
完整示例
1import SwiftUI
2
3struct LinkDemo: View {
4 var body: some View {
5 List {
6 // 基础链接
7 Section("基础用法") {
8 Link("Apple 官网", destination: URL(string: "https://www.apple.com")!)
9 }
10
11 // 自定义标签
12 Section("自定义标签") {
13 Link(destination: URL(string: "https://developer.apple.com")!) {
14 Label("Apple 开发者", systemImage: "apple.logo")
15 }
16 }
17
18 // 自定义 URL 处理
19 Section("自定义处理") {
20 Link("带日志的链接", destination: URL(string: "https://example.com")!)
21 .environment(\.openURL, OpenURLAction { url in
22 print("打开: \(url)")
23 return .handled
24 })
25 }
26
27 // 样式化链接
28 Section("样式化") {
29 Link("超链接样式", destination: URL(string: "https://example.com")!)
30 .buttonStyle(.link)
31 }
32 }
33 }
34}
平台支持
| № | 平台 | 最低版本 |
|---|---|---|
| 0 | iOS | 14.0+ |
| 1 | iPadOS | 14.0+ |
| 2 | Mac Catalyst | 14.0+ |
| 3 | macOS | 11.0+ |
| 4 | tvOS | 14.0+ |
| 5 | visionOS | 1.0+ |
| 6 | watchOS | 7.0+ |
相关类型
- OpenURLAction - 自定义 URL 处理行为的环境值
- OpenURLAction.Resolution - URL 处理结果(handled、peek、discarded)