Here's a very basic way to set an inputAccessoryView
on a UITextField
that's been wrapped in UIViewRepresentable
to use in SwiftUI:
struct ContentView: View {
@State var text = ""
var body: some View {
VStack {
Text("My text field:")
TextFieldWithCustomButtons(text: $text)
.frame(height: 60)
.border(Color.red)
Text(text)
}
}
}
struct TextFieldWithCustomButtons : UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.delegate = context.coordinator
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 44))
customView.backgroundColor = UIColor.red
textField.inputAccessoryView = customView // <--- Here
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
}
func makeCoordinator() -> TextFieldWithCustomButtons.Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: TextFieldWithCustomButtons
init(parent: TextFieldWithCustomButtons) {
self.parent = parent
}
func textFieldDidChangeSelection(_ textField: UITextField) {
parent.text = textField.text ?? ""
}
}
}
Because inputAccessoryView
is a UIView
and I'm not immediately seeing an easy way to get access to a UIViewController
for it, it doesn't seem like there's an obvious solution to embedding SwiftUI in the accessory view. But, if there is a way to embed a UIHostingController
in it, that would give you access to SwiftUI for the accessory view, and not just UIKit.