我有一个代码,我需要从(func textViewDidChangeSelection)到ContentView的TextView的选定范围。我如何在SwiftUI中做这样的事情?
这是我代码的基本思想。
struct ContentView: View {
@State private var text = ""
var body: some View {
UITextViewRepresentable(text: $text)
}
}
struct UITextViewRepresentable: UIViewRepresentable {
let textView = UITextView()
@Binding var text: String
func makeUIView(context: Context) -> UITextView {
textView.delegate = context.coordinator
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
// SwiftUI -> UIKit
uiView.text = text
}
func makeCoordinator() -> Coordinator {
Coordinator(text: $text)
}
class Coordinator: NSObject, UITextViewDelegate {
@Binding var text: String
init(text: Binding<String>) {
self._text = text
}
func textViewDidChange(_ textView: UITextView) {
// UIKit -> SwiftUI
_text.wrappedValue = textView.text
}
func textViewDidChangeSelection(_ textView: UITextView) {
// Fires off every time the user changes the selection.
print(textView.selectedRange)
}
}
}
1条答案
按热度按时间xiozqbni1#
只需为它添加一个
NSRange
类型的额外绑定,因为它是textView.selectedRange
的类型。这意味着在
UIViewRepresentable
上加1:和一个给协调器:
现在在
ContentView
中,可以将其作为@State
: