Swiftui实现richtext字符串并对高亮子字符串添加点击
2024-01-04 本文已影响0人
adrian920
如何仅仅是对部分字符高亮,不需要点击,Group就能实现
Group{Text(“xxx”) + Text(“yyy”)}
使用Group,拼成的Text还可以自动换行
但是,如果想要对高亮的字符串进行点击操作,就要用到AttributedString,下面是一个简单的例子:
var text1: AttributedString {
var text = AttributedString(localized:"登录即表示同意")
text.foregroundColor = .gray
return text
}
var text2: AttributedString {
var text = AttributedString(localized:"用户协议")
text.link = URL(string: "111")
text.foregroundColor = .red
return text
}
var text3: AttributedString {
var text = AttributedString(localized:"和")
text.foregroundColor = .gray
return text
}
var text4: AttributedString {
var text = AttributedString(localized:"隐私协议")
text.link = URL(string: "222")
text.foregroundColor = .red
return text
}
var text: AttributedString {
text1 + text2 + text3 + text4
}
var body: some View {
VStack {
Text(text)
.environment(\.openURL, OpenURLAction { url in
let path = url.absoluteString
if path.hasPrefix("111") {
print("111...")
} else if path.hasPrefix("222") {
print("222...")
}
return .handled
})
}