如何在 SwiftUI 中更改 hyper link 文本颜色

How to change hyper link text color in SwiftUI

我正在尝试使用 SwiftUI 自定义更改给定降价字符串中超链接的默认字体颜色。相当于 UIKit 的 txtString.linkTextAttributes = [ .foregroundColor: UIColor.red ] 的东西。 这是我的代码:


import SwiftUI

struct TextViewAttributedString: View {
    var markdownString: String
    var body: some View {
        Text(convertIntoAttributedString(markdownString:markdownString))
    }
    
    private func convertIntoAttributedString(markdownString: String) -> AttributedString {
        guard var attributedString = try? AttributedString(
            markdown: markdownString,
            options: AttributedString.MarkdownParsingOptions(allowsExtendedAttributes: true,
                                                             interpretedSyntax: .inlineOnlyPreservingWhitespace))
        else {
            return AttributedString(markdownString)
        }
        attributedString.font = .custom("Times New Roman", size: 16, relativeTo: .body)
        
        let runs = attributedString.runs
        for run in runs {
            let range = run.range
            if let textStyle = run .inlinePresentationIntent {
                if textStyle.contains(.stronglyEmphasized) { // .stronglyEmphasized is available
                    // change foreground color of bold text
                    attributedString[range].foregroundColor = .green
                }
                if textStyle.contains(.linkTextAttributes) { // compiler error since .linkTextAttributes not available
                    // change color here but .linkTextAttributes is not available in inlinePresentationIntent
                    // Any other way to change the hyperlink color?
                }
            }
        }
        return attributedString
    }
}

使用 AttribtedString 的示例视图

import SwiftUI

struct AttributedStringView: View {
    let text: String = "**Bold** regular and _italic_ \nnewline\n[hyperlink](www.google.com)"
    var body: some View {
        TextViewAttributedString(markdownString: text)
    }
}

struct AttributedStringView_Previews: PreviewProvider {
    static var previews: some View {
        AttributedStringView()
    }
}

结果: Result Screen

参考文档:https://developer.apple.com/documentation/foundation/attributedstring https://developer.apple.com/videos/play/wwdc2021/10109/

        if run.link != nil {
            // change foreground color of link
            attributedString[range].foregroundColor = .orange
        }

iOS 15: 您可以使用 AttributedString 初始化 SwiftUIs 文本。您可以从降价字符串创建 AttributedString,使用正则表达式找到 link 标签并更改 AttributedString 该部分的颜色。

let markdown = "**Bold** regular and _italic_ [hyperlink cool](www.google.com)"
let linkColor = UIColor.green

var body: some View {
    Text(makeAttributedString())
}

func makeAttributedString() -> AttributedString {
    var string = (try? AttributedString(markdown: markdown)) ?? AttributedString("Error markdown")
    let linkLabels = getLinkLabels(markdownString: markdown)
    for label in linkLabels {
        if let range = string.range(of: label) {
            string[range].foregroundColor = linkColor
        }
    }
    return string
}

func getLinkLabels(markdownString: String) -> [String] {
    guard let regex = try? NSRegularExpression(pattern: "\[[a-zA-Z0-9_ ]*\]") else { return [] }
    let results = regex.matches(in: markdownString,
                                range: NSRange(markdownString.startIndex..., in: markdownString))
    let labels = results.compactMap {
        Range([=10=].range, in: markdownString).map { String(markdownString[[=10=]]) }
    }
    // removing the brackets from the link labels before return
    return labels.map { [=10=].trimmingCharacters(in: CharacterSet(charactersIn: "[]")) }
}