Eth*_*Kay 6 xcode swift swiftui
在 Swift 5.5 SwiftUI 中,现在可以在 Markdown 文本中包含链接。是否可以使用它为Text视图中的子文本添加点击处理程序?例如,我正在想象做如下的事情,但我还没有弄清楚如何构建一个适用于此目的的链接(我每次都会收到 URL 错误)。设置某种自定义 url 架构是否有效?有没有更好的解决方案可以做到这一点,比如我可以添加到与sText类似的视图中?目标是解决与此处提到的类似问题,但不必回退到 UITextView 或非包装 HStack 或带有 ZStack 的 GeometryReaders。UITextViewshouldInteractWith
let baseText = "apple banana pear orange lemon"
let clickableText = baseText.split(separator: " ")
.map{ "[\($0)](domainThatImAllowedToCapture.../\($0))" }
Text(.init(clickableText)).onOpenLink { link in
print(link.split(separator: "/").last) // prints "pear" if word pear is tapped.
}
Run Code Online (Sandbox Code Playgroud)
wor*_*dog 19
你可以尝试类似这个示例代码的东西。它循环您的baseText,创建适当的链接,当链接被点击/操作时,您可以添加更多代码来处理它。
struct ContentView: View {
let baseText = "apple banana pear orange lemon"
let baseUrl = "https://api.github.com/search/repositories?q="
var body: some View {
let clickableText = baseText.split(separator: " ").map{ "[\($0)](\(baseUrl)\($0))" }
ForEach(clickableText, id: \.self) { txt in
let attributedString = try! AttributedString(markdown: txt)
Text(attributedString)
.environment(\.openURL, OpenURLAction { url in
print("---> link actioned: \(txt.split(separator: "=").last)" )
return .systemAction
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5732 次 |
| 最近记录: |