truct CustomTextfield: UIViewRepresentable { @Binding var text: String var keyType: UIKeyboardType func makeUIView(context: Context) -> UITextField { let textfield = UITextField() textfield.keyboardType = keyType textfield.textAlignment = .center textfield.delegate = context.coordinator let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: textfield.frame.size.width, height: 44)) let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil) let doneButton = UIBarButtonItem(title: "確定", style: .done, target: self, action: #selector(textfield.doneButtonTapped(button:))) toolBar.items = [flexibleSpace, doneButton] toolBar.setItems([flexibleSpace, doneButton], animated: true) textfield.inputAccessoryView = toolBar return textfield } func updateUIView(_ uiView: UITextField, context: Context) { uiView.text = text } func makeCoordinator() -> CustomTextfield.Coordinator { Coordinator(self) } class Coordinator: NSObject, UITextFieldDelegate { var control: CustomTextfield init(_ control: CustomTextfield) { self.control = control } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { self.control.text = textField.text! return true } } }