Vij*_*ama 6 swift swiftui ios15 attributedstring
我正在尝试使用 SwiftUI 自定义更改给定 Markdown 字符串中超链接的默认字体颜色。相当于txtString.linkTextAttributes = [ .foregroundColor: UIColor.red ]
UIKit 的东西。这是我的代码:
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
}
}
Run Code Online (Sandbox Code Playgroud)
使用 AttributedString 的示例视图
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()
}
}
Run Code Online (Sandbox Code Playgroud)
结果: 结果屏幕
参考文档:https://developer.apple.com/documentation/foundation/attributedstring https://developer.apple.com/videos/play/wwdc2021/10109/
对我来说最简单的解决方案是:
Text(.init("some text **[google.com](https://google.com)**"))
.accentColor(.red)
Run Code Online (Sandbox Code Playgroud)
if run.link != nil {
// change foreground color of link
attributedString[range].foregroundColor = .orange
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4234 次 |
最近记录: |