Extend SwiftUI Keyboard with Custom Button

前端 未结 3 1596
醉话见心
醉话见心 2020-12-28 18:32

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

3条回答
  •  情书的邮戳
    2020-12-28 18:56

    If there is an issue with @Binding implement the Coordinator class which conforms to the UITextFieldDelegate. This will allow one to be able to customize the TextField further if required.

    struct DecimalTextField: UIViewRepresentable {
         private var placeholder: String
         @Binding var text: String
    
         init(_ placeholder: String, text: Binding) {
            self.placeholder = placeholder
            self._text = text
         } 
    
         func makeUIView(context: Context) -> UITextField {
            let textfield = UITextField()
            textfield.keyboardType = .decimalPad
            textfield.delegate = context.coordinator
            textfield.placeholder = placeholder
            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
         }
    
         func makeCoordinator() -> Coordinator {
            Coordinator(self)
         }
    
         class Coordinator: NSObject, UITextFieldDelegate {
            var parent: DecimalTextField
        
         init(_ textField: DecimalTextField) {
            self.parent = textField
         }
        
         func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
             if let currentValue = textField.text as NSString? {
                 let proposedValue = currentValue.replacingCharacters(in: range, with: string) as String
                 self.parent.text = proposedValue
             }
             return true
         }
       }
     }
    

提交回复
热议问题