在此之前我会说我的 Swift 和 SwiftUI 经验非常有限,所以我可能错过了一些明显的事情。
我的问题分为多个关注领域
一些背景
我有几段文本,每段都来自我想提供链接的特定来源。链接应与文本内联并位于每个段落的末尾,并且格式应为“Source
Text(.init("[Source](https://example.com)"))
。这已经让我走了很远,但我错过了将图标作为链接标签的一部分包含在内的关键步骤。截至目前,我被迫在实际链接文本后面添加图标,如下例所示。
所以我的问题归结为:有没有办法在 SwiftUI 中渲染 markdown 字符串内的图像?
我的代码设置的简化示例
import SwiftUI
struct Paragraph {
text: String
url: String
}
struct ParagraphView: View {
let paragraph: Paragraph
var body: some View {
Text(paragraph.text)
// Less than ideal solution I have currently
+ Text(.init(" [Source](\(paragraph.url)) "))
+ Text(Image(systemName: "star")) // Example icon
}
}
理想情况下,我想做这样的事情
struct ParagraphView: View {
let paragraph: Paragraph
var body: some View {
Text(paragraph.text)
+ Text(.init(" [Source \(IMAGE)](\(paragraph.url))"))
}
}
我尝试使用 AttributedString 和 NSAttributedString 来实现此目的
struct ParagraphView: View {
let paragraph: Paragraph
var markdown: String {
let str = NSMutableAttributedString(string: " [Source ")
let iconAttachment = NSTextAttachment()
iconAttachment.image = UIImage(systemName: "star")
let iconText = NSAttributedString(attachment: iconAttachment)
str.append(iconText)
str.append(NSAttributedString(string: "](\(paragraph.url))"))
return str.string
}
var body: some View {
Text(paragraph.text)
// Link works, but image is not rendered
+ Text(.init(markdown))
}
}
不使用 Markdown 来显示图像, 您可以尝试使用不同的方法,使用两个
HStack
一个 .onTapGesture
和 openURL
,
如示例代码所示。
struct ParagraphView: View {
@Environment(\.openURL) private var openURL
let paragraph: Paragraph
var body: some View {
HStack {
Text(paragraph.text)
HStack {
Text("Source")
Image(systemName: "star")
}.foregroundStyle(.blue)
.onTapGesture {
if let url = URL(string: "\(paragraph.url)") {
openURL(url)
}
}
}
}
}
struct Paragraph {
var text: String = "paragraph text"
var url: String = "https://www.apple.com/"
}
struct ContentView: View {
var body: some View {
ParagraphView(paragraph: Paragraph())
}
}