如果文本在聊天屏幕中包含 URL,有没有办法突出显示文本并可点击
发件人用户代码:-
import SwiftUI
struct TextHighlightURL: View {
var body: some View {
HStack(alignment: .bottom){
Spacer()
Text("2:22 PM").font(.system(size: 10))
.foregroundColor(.gray)
HStack {
Text("www.google.com")
.foregroundColor(.white)
.multilineTextAlignment(.trailing)
.padding(10)
}
.background(Color.init("DTR-ChatSendrColor"))
.cornerRadius(10.0)
}.padding(.vertical,5)
.padding()
}
}
输出:-
接收者用户代码:-
struct SenderReciverUI1: View {
var body: some View {
Group {
HStack(alignment: .bottom){
VStack(alignment: .leading,spacing:5) {
HStack(alignment: .bottom) {
Text("www.google.com")
.foregroundColor(.white)
.padding(10)
.cornerRadius(10.0)
}
}
Spacer()
}.padding(.vertical,5)
.padding()
}
}
}
我的目标:-
有人可以向我解释一下,如果发送者发送链接并且接收者收到链接,它会自动突出显示,并且如果文本包含 URL 则可点击,则如何显示从两侧突出显示文本,我已尝试按上述方式实现,但尚未结果。
任何帮助将不胜感激。
提前致谢。
您需要为
UIViewRepresentable
创建自定义 TextView
。
检查下面的代码,这可能对您有帮助。
struct TextView: UIViewRepresentable {
@Binding var text: String
@Binding var textStyle: UIFont.TextStyle
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.font = UIFont.preferredFont(forTextStyle: textStyle)
textView.autocapitalizationType = .sentences
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.isEditable = false
textView.dataDetectorTypes = .link
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
uiView.font = UIFont.preferredFont(forTextStyle: textStyle)
}
func makeCoordinator() -> Coordinator {
Coordinator($text)
}
class Coordinator: NSObject, UITextViewDelegate {
var text: Binding<String>
init(_ text: Binding<String>) {
self.text = text
}
func textViewDidChange(_ textView: UITextView) {
self.text.wrappedValue = textView.text
}
}
}
在您的“接收者用户代码:-”与“发送者用户代码”
相同struct SenderReciverUI1: View {
@State private var message = "Hello, www.google.com. this is just testing for hyperlinks, check this out our website https://www.apple.in thank you."
@State private var textStyle = UIFont.TextStyle.body
var body: some View {
Group {
HStack(alignment: .bottom){
VStack(alignment: .leading,spacing:5) {
HStack(alignment: .bottom) {
TextView(text: $message, textStyle: $textStyle)
.foregroundColor(.white)
.padding(10)
.cornerRadius(10.0)
}
}
Spacer()
}.padding(.vertical,5)
.padding()
}
}
}
如果您需要什么,请告诉我。
当您调用
Text(myString)
时,SwiftUI 实际上使用 Text<S>(_ content: S) where S : StringProtocol
初始化程序。要突出显示链接并使它们可单击,您可以强制使用具有此属性的 Text(_:tableName:bundle:comment:)
初始化程序。
示例:
let myStringWithLink = "My link: https://stackoverflow.com"
Text(LocalizedStringKey(myStringWithLink))