在 Swift 5.5 SwiftUI 中,現在可以在 markdown 文本中添加鏈接。是否可以使用它為Text視圖中的潛文本添加點擊處理程式?例如,我正在想象做如下的事情,但我還沒有弄清楚如何構建一個適用于此的鏈接(我每次都會收到 URL 錯誤)。設定某種自定義 url 架構會起作用嗎?有沒有更好的解決方案,比如我可以添加到Text類似于UITextView's的視圖中shouldInteractWith?目標是解決與此處提到的類似的問題,但不必回退到 UITextView 或使用 ZStacks 的非包裝 HStacks 或 GeometryReaders。
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.
}
uj5u.com熱心網友回復:
您可以嘗試類似此示例代碼的內容。它遍歷您的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
})
}
}
}
uj5u.com熱心網友回復:
使用@workingdog 描述的方法,我已將其清理為以下作業解決方案:
import SwiftUI
struct ClickableText: View {
@Environment(\.colorScheme) var colorScheme: ColorScheme
private var text: String
private var onClick: (_ : String) -> Void
init(text: String, _ onClick: @escaping (_ : String) -> Void) {
self.text = text
self.onClick = onClick
}
var body: some View {
Text(.init(toClickable(text)))
.foregroundColor(colorScheme == .dark ? .white : .black)
.accentColor(colorScheme == .dark ? .white : .black)
.environment(\.openURL, OpenURLAction { url in
let trimmed = url.path
.replacingOccurrences(of: "/", with: "")
.trimmingCharacters(in: .letters.inverted)
withAnimation {
onClick(trimmed)
}
return .discarded
})
}
private func toClickable(_ text: String) -> String {
// Needs to be a valid URL, but otherwise doesn't matter.
let baseUrl = "https://a.com/"
return text.split(separator: " ").map{ word in
var cleaned = String(word)
for keyword in ["(", ")", "[", "]"] {
cleaned = String(cleaned.replacingOccurrences(of: keyword, with: "\\\(keyword)"))
}
return "[\(cleaned)](\(baseUrl)\(cleaned))"
}.joined(separator: " ")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/411914.html
標籤:
上一篇:swift的擴展范圍是什么?
