You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中能否用AttributedString链接跳转至应用内视图?

实现AttributedString触发应用内页面跳转

当然可以实现!你可以通过自定义AttributedString的链接属性,结合SwiftUI的onOpenURL修饰器来完成应用内页面跳转,具体步骤如下:

1. 定义应用内专属URL Scheme

先为跳转目标页面定义一个自定义的URL Scheme,比如myapp://viewb,用来标识要跳转到ViewB的动作。

2. 构建带自定义链接的AttributedString

用Markdown语法创建包含自定义链接的AttributedString,写法和外部链接类似:

let attributedText = try! AttributedString(markdown: "点击前往[ViewB](myapp://viewb)")

3. 在ViewA中处理跳转逻辑

在ViewA里展示这个AttributedString,同时通过onOpenURL监听链接点击事件,触发页面跳转:

struct ViewA: View {
    @State private var showViewB = false
    
    var body: some View {
        Text(attributedText)
            .onOpenURL { url in
                // 判断是否为目标跳转链接
                if url.scheme == "myapp" && url.host == "viewb" {
                    showViewB = true
                }
            }
            // 以弹窗形式展示ViewB,也可以用navigationLink等方式
            .sheet(isPresented: $showViewB) {
                ViewB()
            }
    }
}

struct ViewB: View {
    var body: some View {
        Text("这是ViewB页面")
            .font(.title)
    }
}

效果说明

这种实现逻辑和你提到的外部链接写法几乎一致,只是把外部URL替换成了应用内自定义的Scheme。点击带链接的文本后,就能触发ViewA到ViewB的跳转,和Twitter中点击文本跳转至用户主页、详情页的效果逻辑完全匹配。

示例效果参考:
Twitter样式的应用内跳转示例

内容的提问来源于stack exchange,提问作者M Alamin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 13:11:12