我正在尝试用SwiftUI自定义更改给定markdown字符串中超链接的默认字体颜色。类似于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/attributedstringhttps://developer.apple.com/videos/play/wwdc2021/10109/
3条答案
按热度按时间zf9nrax11#
vc6uscn92#
**iOS 15:**您可以使用AttributedString初始化SwiftUI文本。您可以从markdown字符串创建AttributedString,使用regex查找链接标签,并更改AttributedString中该部分的颜色。
l7mqbcuq3#
我必须替换AttributeContainer。