Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend SwiftUI Keyboard with Custom Button

Tags:

I'm trying to find a way to add a key or button to the SwiftUI numberPad. The only references I have found say it is not possible. In the Swift world I added a toolbar with a button to dismiss the keyboard or perform some other function.

I would even build a ZStack view with the button on top but I can't find a way to add the numberPad to my own view.

All I'm really trying to do in this case is dismiss the numberPad when the data is entered. I first attempted to modify the SceneDelegate to dismiss on taps, but that only works if I tap in another text or textfield view not in open space on the view.

window.rootViewController = UIHostingController(rootView: contentView.onTapGesture {     window.endEditing(true) }) 

Ideally, I'd add a Done key to the lower left space. Second best add a toolbar if it can be done in SwiftUI.

enter image description here

Any guidance would be appreciated.

Xcode Version 11.2.1 (11B500)

like image 510
JohnSF Avatar asked Nov 23 '19 00:11

JohnSF


1 Answers

Solved the issue using UIRepresentable protocol

struct TestTextfield: UIViewRepresentable {     @Binding var text: String     var keyType: UIKeyboardType     func makeUIView(context: Context) -> UITextField {         let textfield = UITextField()       textfield.keyboardType = keyType         let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44))         let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(textfield.doneButtonTapped(button:)))         toolBar.items = [doneButton]         toolBar.setItems([doneButton], animated: true)         textfield.inputAccessoryView = toolBar         return textfield     }          func updateUIView(_ uiView: UITextField, context: Context) {         uiView.text = text              } }  extension  UITextField{     @objc func doneButtonTapped(button:UIBarButtonItem) -> Void {        self.resignFirstResponder()     }  } 

Using in content view

struct ContentView : View {     @State var text = ""          var body: some View {         TestTextfield(text: $text, keyType: UIKeyboardType.phonePad)             .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 50)             .overlay(                 RoundedRectangle(cornerRadius: 16)                     .stroke(Color.blue, lineWidth: 4)         )     } } 
like image 106
Rajeev Kumar S Avatar answered Sep 22 '22 02:09

Rajeev Kumar S