link
好的 👍 我幫你整理 Swift 裡面 Link 的寫法,這通常用在 SwiftUI 中,讓你可以在 App 裡打開網址(例如 Safari)。
🔗 SwiftUI 的 Link
Link 是 SwiftUI 內建的元件,用來顯示一個文字或按鈕,點擊後會開啟指定的 URL。
最基本的寫法
import SwiftUI
struct ContentView: View {
var body: some View {
Link("打開 Apple 官網", destination: URL(string: "https://www.apple.com")!)
}
}
效果:顯示一個文字,點下去會跳到 Safari 開啟 Apple 官網。
使用自訂樣式(例如 Button 樣式)
Link(destination: URL(string: "https://www.google.com")!) {
Label("Google", systemImage: "globe")
}
.font(.title2)
.foregroundColor(.blue)
效果:一個帶圖示的連結,看起來就像按鈕。
在 List 或 NavigationView 中使用
List {
Link("Swift 官網", destination: URL(string: "https://swift.org")!)
Link("Swift Playgrounds", destination: URL(string: "https://apps.apple.com/swift-playgrounds")!)
}
會顯示在列表中,點擊就能跳轉。
用 Button 模擬 Link(想要更多控制時)
如果想在 App 內自訂開啟方式(例如不跳 Safari,而是用 SFSafariViewController),就不適合用 Link,而是用 Button + UIApplication.shared.open:
Button("打開 OpenAI") {
if let url = URL(string: "https://openai.com") {
UIApplication.shared.open(url)
}
}
✅ 總結
Link→ 最簡單的方式,直接顯示可點擊文字或自訂內容。Label搭配Link→ 可以做成帶 icon 的連結。Button + UIApplication.shared.open→ 如果要更細控制(例如在 App 內開 SafariViewController)。
好,我幫你整理一個 Swift 開網址的對照表,把 Link 和 Button + UIApplication.shared.open 放在一起比較:
🔗 Swift 開網址的兩種方式比較
👉 簡單來說:
- 想快速顯示連結 → 用
Link - 想要控制開啟方式(例如內嵌網頁、攔截 URL) → 用
Button + UIApplication.shared.open