我想知道如何在SwiftUI文本中添加按钮和链接。举个例子:在一个很长的文本中,一些特殊的词是按钮或链接,就像维基百科上的一篇文章:
有一些蓝色标记为链接的单词,我如何在SwiftUI中访问它?
谢谢,Boothosh
发布于 2021-08-11 11:39:52
我知道这是多么痛苦!我花了很多时间在互联网上阅读关于如何做同样的事情的文章,发现了最简单的解决方案。
解决方案here的参考
1.添加TextView(...)添加到您的项目
/// Text view with click able links
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 DetailsView: View {
@State var text : String = "Yo.. try https://google.com"
@State private var textStyle = UIFont.TextStyle.body
var body: some View {
TextView(text: $text, textStyle: $textStyle)
}
}
https://stackoverflow.com/questions/67610667
复制相似问题