2012-04-09 39 views
45

ACTUALIZACIÓN:¿Cómo agregar el botón Hecho al teclado?

También probé la implementación UITextViewDelegate delegado y luego haciendo en mi controlador:

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

que también estableció el delegado de la vista de texto para ser auto (instancia de vista controlador).

Al hacer clic en el botón Listo todavía inserta simplemente una nueva línea :(


ACTUALIZACIÓN:

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 la toma de corriente.

Luego lo hice:


self.myTextView.delegate = self; 

Y:

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

Pero cuando hago clic en el botón Hecho, que sólo añade 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 cerrar el teclado.

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

+7

Investigue un poco antes de publicar aquí. Un google para el botón 'UITextField done' arroja muchos resultados relevantes, incluido este http://coderslike.us/2009/03/09/dismissing-keyboard-for-uitextfield/ – joerick

+0

@joerick Intenté su enlace. Cuando hago clic en el botón Listo, solo inserta una nueva línea. –

+0

Muéstranos lo que tienes hasta ahora; publica el código que estás usando en este momento, y luego podemos ver lo que podrías estar haciendo mal. – joerick

Respuesta

109

eso es bastante simple :)

[textField setReturnKeyType:UIReturnKeyDone]; 

para despedir el teclado implementar el protocolo <UITextFieldDelegate> en su clase, establecen

textfield.delegate = self; 

y utilizar

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

o

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

Hice todo eso y presioné el botón Listo para insertar una nueva línea. Verifique mi pregunta actualizada. –

+1

hola, debe poder averiguar qué salió mal. código para un UITextField, y lo copió para su UITextView sin cambiarlo. Utilice un 'UITextField', implemente' 'y use el código que le proporcioné :) un UITextView no puede usar el UITextFieldDelegate, por supuesto. , sin embargo, puede usar el protocolo '' si realmente desea mantener la vista de texto. más información: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html –

+0

Gracias. He utilizado UITextVieDelegate y funciona. Una pregunta. ¿Es posible permitir múltiples líneas y también tener un botón hecho para cerrar el teclado? Quiero decir, ¿es posible tener botones de retorno y hechos? –

-2

En el Generador de interfaces en las propiedades de la vista de texto puede establecer el tipo de botón de retorno como Listo.

Luego hay que comprobar cuando se pulsa el botón Volver usando

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

Comprobar si el texto == "/ n", entonces ocultar el teclado al renunciar primer nivel de respuesta en su Textview.

14

Entre en su guión gráfico, seleccione su campo de texto y en el Inspector de atributos hay una opción que dice "devolver clave" ... seleccione "Hecho".

Entonces entra en su ViewController y añadir:

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

luego volver a su campo de texto, haga clic en puntos de venta y enlace "puso fin a la salida" a la acción dismissKeyboard.

+0

gracias Mike tu respuesta me ayudó en mi aplicación. Te di un voto positivo y gracias. adrian –

1

Establezca la opción 'Return Key' en la opción text field en el inspector del campo de texto. A continuación, haga clic derecho en el campo de texto y mientras mantiene CTRL, seleccione 'Did End On Exit' y arrástrelo al archivo view controllers. Esto creará un método IBAction. Dar el método un nombre y luego introduzca los siguientes valores:

[textField becomeFirstResponder]; 
[textField resignFirstResponder]; 

Su método debe tener este aspecto:

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

Ok, así que yo también he estado luchando con este mismo asunto. Actualmente estoy accediendo a una UITextView en una UITableViewCell (a través de etiquetas). Debido a que estoy usando células prototipo, no puedo usar IBActions ni IBOutlets como todo el mundo sugiere. En cambio, estoy usando;

- (BOOL) Textview: (UITextView *) Textview shouldChangeTextInRange: (NSRange) variar replacementText: (NSString *) Texto

Esto entonces me proporcione el texto cada vez que el usuario realiza un botón. Mi solución entonces fue obtener el personaje ascii para la nueva línea; "/norte". Si ese es el texto que se ingresó, renunciaré 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 tendrá esta solución hacky, pero pensé que había que ponerlo ahí por si alguien lo necesita!

9

versión Swift:

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 
    } 
} 
0

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

textField.returnKeyType = UIReturnKeyDone; 
10

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

Esta es una manera más segura y más limpia de agregar el botón Hecho a cualquier Tipo de teclado. Cree UIToolBar, agregue el botón Listo y establezca 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; 

IBAction para el botón 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) 
    } 
+0

Awesome !!! Es realmente una solución magnífica. – Genevios

0

El siguiente es mi enfoque, en Swift 3. Cuando el doneBtn hizo clic, déjelo enviar el evento .editingDidEndOnExit. Uso este evento para manejar el problema de foco entre múltiples textFields.

// 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) 
    } 
} 
Cuestiones relacionadas