ios iphone objective-c xcode programmatically-created

ios - ¿Cómo agregar el botón Hecho al teclado?



iphone objective-c (9)

ACTUALIZAR:

También intenté implementar el delegado UITextViewDelegate y luego hacerlo en mi controlador:

- (BOOL)textViewShouldEndEditing:(UITextView *)textView { [textView resignFirstResponder]; return YES; }

También configuro el delegado de la vista de texto como auto (instancia de vista de controlador).

Al hacer clic en el botón Hecho todavía se inserta solo una nueva línea :(

ACTUALIZAR:

Lo que he hecho hasta ahora. He implementado un UITextFieldDelegate por mi controlador de vista.

He conectado la vista de texto al controlador de vista a través de un tomacorriente.

Entonces hice

self.myTextView.delegate = self;

Y:

- (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; }

Pero cuando hago clic en el botón Listo, solo agrega una nueva línea.

Así que tengo un elemento UITextView en mi escena y cuando un usuario lo toca, aparece el teclado y se puede editar.

Sin embargo, no puedo descartar el teclado.

¿Cómo puedo agregar el botón Hecho al teclado para que se pueda descartar?


Configure la opción ''Return Key'' debajo de la opción de text field en el inspector para su campo de texto. Luego, haga clic con el botón derecho en el campo de texto y mientras mantiene presionada la CTRL seleccione ''Did End On Exit'' y arrástrelo al archivo de view controllers . Esto creará un método IBAction . Asigne un nombre al método y luego ingrese los siguientes valores:

[textField becomeFirstResponder]; [textField resignFirstResponder];

Tu método debería verse así:

- (IBAction)methodName:(id)sender; { [sender becomeFirstResponder]; [sender resignFirstResponder]; }


El siguiente es mi enfoque, en Swift 3 . Cuando el doneBtn clic, deje que envíe el evento .editingDidEndOnExit . Uso este evento para manejar el problema de enfoque entre varios campos de texto.

// My customized UITextField class MyTextField: UITextField { override func awakeFromNib() { super.awakeFromNib() // Add toolBar when keyboardType in this set. let set : [UIKeyboardType] = [.numberPad, .phonePad] if (set.contains(self.keyboardType) ) { self.addDoneToolbar() } } // Add a toolbar with a `Done` button func addDoneToolbar() { let toolbar = UIToolbar() let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onToolBarDone)) toolbar.items = [space, doneBtn] toolbar.sizeToFit() self.inputAccessoryView = toolbar } @objc func onToolBarDone() { // I use `editingDidEndOnExit` to simulate the `Done` behavior // on the original keyboard. self.sendActions(for: .editingDidEndOnExit) } }


En Interface Builder, en las propiedades de textView, puede establecer el tipo de botón de retorno en Listo.

A continuación, debe comprobar cuándo se presiona el botón de retorno con

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

Verifique si el texto == "/ n" luego descarte el teclado renunciando al primer respondedor en su textView.


Esta es la mejor manera de agregar el botón Hecho en el teclado

textField.returnKeyType = UIReturnKeyDone;


Ok, entonces yo también he estado luchando con este problema. Actualmente estoy accediendo a un UITextView en un UITableViewCell (a través de etiquetas). Debido a que estoy usando celdas prototipo, no puedo usar IBActions ni IBOutlets como todos sugieren. En cambio, estoy usando;

- (BOOL) textView: (UITextView *) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString *) text

Esto me proporcionará el texto cada vez que el usuario presione un botón. Mi solución entonces, era obtener el carácter ascii para la nueva línea; "/norte". Si ese es el texto que se ingresó, renunciaría al primer respondedor. Por ejemplo;

// If the text length is 0 then the user is deleting something, so only check the ascii character if there is text to check if (text.length != 0) { // Get the Ascii character int asciiCode = [text characterAtIndex:0]; // If the ascii code is /n or new line, then resign first responder if (asciiCode == 10) { [alertTextView resignFirstResponder]; [DeviceTextView resignFirstResponder]; } }

No estoy seguro de si alguien más va a necesitar esta solución intrépida, ¡pero pensé que la pondría por ahí en caso de que alguien la necesite!


Vaya a su guión gráfico, seleccione su campo de texto y debajo del Inspector de atributos hay una opción que dice "tecla de retorno" ... seleccione "Listo".

Luego entra en tu ViewController y agrega:

- (IBAction)dismissKeyboard:(id)sender; { [textField becomeFirstResponder]; [textField resignFirstResponder]; }

Luego regrese a su campo de texto, haga clic en puntos de venta y enlace "Terminó al salir" para descartar la acción de Keyboard.


Versión rápida:

En su ViewController:

textField.returnKeyType = UIReturnKeyType.Done textField.delegate = self

Después de su ViewController

extension MyViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }


eso es bastante simple :)

[textField setReturnKeyType:UIReturnKeyDone];

para descartar el teclado implemente el protocolo <UITextFieldDelegate> en su clase, establezca

textfield.delegate = self;

y use

- (void)textFieldDidEndEditing:(UITextField *)textField { [textField resignFirstResponder]; }

o

- (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; }


Agregue UIToolBar como vista personalizada que tendrá el botón Hecho como UIBarButtonItem en él.

Esta es una forma más segura y limpia de agregar el botón Hecho a cualquier tipo de teclado. Cree UIToolBar agregue el botón Hecho y configure inputAccessoryView de cualquier UITextField o UITextView.

UIToolbar *ViewForDoneButtonOnKeyboard = [[UIToolbar alloc] init]; [ViewForDoneButtonOnKeyboard sizeToFit]; UIBarButtonItem *btnDoneOnKeyboard = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(doneBtnFromKeyboardClicked:)]; [ViewForDoneButtonOnKeyboard setItems:[NSArray arrayWithObjects:btnDoneOnKeyboard, nil]]; myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard;

Botón IBAction For Done

- (IBAction)doneBtnFromKeyboardClicked:(id)sender { NSLog(@"Done Button Clicked."); //Hide Keyboard by endEditing or Anything you want. [self.view endEditing:YES]; }

SWIFT 3

var ViewForDoneButtonOnKeyboard = UIToolbar() ViewForDoneButtonOnKeyboard.sizeToFit() var btnDoneOnKeyboard = UIBarButtonItem(title: "Done", style: .bordered, target: self, action: #selector(self.doneBtnFromKeyboardClicked)) ViewForDoneButtonOnKeyboard.items = [btnDoneOnKeyboard] myTextField.inputAccessoryView = ViewForDoneButtonOnKeyboard

Función

@IBAction func doneBtnFromKeyboardClicked (sender: Any) { print("Done Button Clicked.") //Hide Keyboard by endEditing or Anything you want. self.view.endEditing(true) }