有没有最新的方法来转换文本内的链接?我从 API 中获取此类文本:
var someText: String = "with banks (for example to the sometimes controversial but leading exchange <a href="https://www.coingecko.com/en/exchanges/bitfinex">Bitfinex</a>)."
Run Code Online (Sandbox Code Playgroud)
如何将该链接转换为具有正确名称的可点击链接(在上面的示例中:Bitfinex)?
文本可以包含多个链接。SwiftUI 现在支持 markdown,手动我可以这样做:
Text("[Privacy Policy](https://example.com)")
Run Code Online (Sandbox Code Playgroud)
但是我该如何处理从 api 接收到的带有多个链接的文本呢?
寻找 Swift 5 和 SwiftUI 3 解决方案。
你所拥有的是一个 html 字符串。NSAttributedString
您可以使用初始值设定项选项解释 html 字符串NSAttributedString.DocumentType.html
,并用它初始化一个新的 AttributedString。无需操作和/或手动解析您的字符串:
首先将此扩展添加到您的项目中:
extension StringProtocol {
func htmlToAttributedString() throws -> AttributedString {
try .init(
.init(
data: .init(utf8),
options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
],
documentAttributes: nil
)
)
}
}
Run Code Online (Sandbox Code Playgroud)
然后扩展Text
以添加自定义初始值设定项:
extension Text {
init(html: String, alert: String? = nil) {
do {
try self.init(html.htmlToAttributedString())
} catch {
self.init(alert ?? error.localizedDescription)
}
}
}
Run Code Online (Sandbox Code Playgroud)
import SwiftUI
struct ContentView: View {
var html = #"with banks (for example to the sometimes controversial but leading exchange <a href="https://www.coingecko.com/en/exchanges/bitfinex">Bitfinex</a>. For more info <a href="https://www.google.com/">Google</a>).""#
var body: some View {
Text(html: html)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2353 次 |
最近记录: |