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

SwiftUI中为高亮超链接添加下划线的实现方法

SwiftUI中为高亮超链接添加下划线的实现方法

当然可以搞定!在SwiftUI里给超链接同时加上高亮和下划线,有两种很实用的方案,我给你详细说说:

方法一:用AttributedString精准定制链接样式

这种方式能让你完全掌控链接文本的样式,操作起来也很直观:

import SwiftUI

struct ContentView: View {
    var body: some View {
        let fullText = "This link goes to google"
        var attributedText = AttributedString(fullText)
        
        // 定位到要设置为链接的文本片段
        if let linkRange = attributedText.range(of: "link") {
            // 设置跳转的目标链接
            attributedText[linkRange].link = URL(string: "https://google.com")
            // 添加实心蓝色下划线
            attributedText[linkRange].underlineStyle = Text.LineStyle(pattern: .solid, color: .blue)
            // 设置链接的高亮颜色
            attributedText[linkRange].foregroundColor = .blue
        }
        
        Text(attributedText)
    }
}

要是你想把下划线改成虚线,或者换个颜色,直接调整underlineStyle的参数就行,灵活性拉满。

方法二:结合Markdown写法批量处理链接

如果你习惯用Markdown语法写链接,也可以先把Markdown文本转成AttributedString,再给所有链接统一加上下划线:

import SwiftUI

struct ContentView: View {
    var body: some View {
        // 把Markdown文本解析为AttributedString
        guard var attributedText = try? AttributedString(markdown: "This [link](https://google.com) goes to google") else {
            return Text("This link goes to google")
        }
        
        // 遍历所有带链接的文本片段,添加下划线样式
        for run in attributedText.runs where run.link != nil {
            attributedText[run.range].underlineStyle = Text.LineStyle(pattern: .solid, color: .blue)
        }
        
        Text(attributedText)
            .tint(.blue) // 统一设置链接的高亮颜色
    }
}

这种方法适合文本里有多个链接的场景,不用一个个手动定位文本范围,省事儿不少。

需要注意的是,这两种方法都要求iOS 15及以上系统,现在大部分项目都已经适配到这个版本了,放心用就行~

备注:内容来源于stack exchange,提问作者tHatpart

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 12:58:06