I am trying to implement an inputAccessoryView on a TextField in SwiftUI. The goal is to have a \"Done\" Button appear above the Keyboard which when pressed gets rid of the
struct InputAccessory: UIViewRepresentable {
var placeHolder: String
func makeUIView(context: Context) -> UITextField {
let toolbar = UIToolbar()
toolbar.setItems([
// just moves the Done item to the right
UIBarButtonItem(
barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace
, target: nil
, action: nil
)
, UIBarButtonItem(
title: "Done"
, style: UIBarButtonItem.Style.done
, target: self
, action: nil
)
]
, animated: true
)
toolbar.barStyle = UIBarStyle.default
toolbar.sizeToFit()
let customView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 44))
customView.backgroundColor = UIColor.red
let sampleTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
sampleTextField.inputAccessoryView = toolbar
sampleTextField.placeholder = placeHolder
return sampleTextField
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.endEditing(true)
}
}
struct ContentView : View {
@State var email:String = "e"
var body: some View {
HStack{
Circle()
InputAccessory(placeHolder: "hello")
Circle()
}
}
}
PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())
Now you can hide and show the textfield with the "showInput" state. The next problem is, that you have to open your keyboard at a certain event and show the textfield. That's again not possible with SwiftUI and you have to go back to UiKit and making it first responder. Overall, at the current state it's not possible to work with the keyboard or with the certain textfield method.