如果我使用TextField,但不使用UITextView,工具栏会显示出来.我不确定这是一个错误,还是我没有正确地将UITextView与SwiftUI连接起来.有没有关于如何使.bar()与UITextView一起工作的 idea ?以下是我的代码:
struct MyUITextView: UIViewRepresentable {
@Binding var text: String
private let editor = UITextView()
func makeUIView(context: Context) -> UITextView {
editor.delegate = context.coordinator
return editor
}
func makeCoordinator() -> Coordinator {
Coordinator(text: $text)
}
func updateUIView(_ editor: UITextView, context: Context) {
editor.text = text
}
class Coordinator: NSObject, UITextViewDelegate {
@Binding private var text: String
init(text: Binding<String>) {
self._text = text
}
func textViewDidChange(_ editor: UITextView) {
text = editor.text
}
}
}
struct ContentView: View {
@State var uitextView = "UITextView"
@State var textfield = "TextField"
var body: some View {
VStack {
MyUITextView(text: $uitextView) // Toolbar doesn't show up when focused
.border(.black, width: 1)
.frame(maxHeight: 40)
TextField("", text: $textfield) // Toolbar shows up when focused
.border(.black, width: 1)
}
.toolbar {
ToolbarItem(placement: .keyboard) {
Button("Click") {}
}
}
}
}
Demo个