¿Cómo descartar el teclado para UITextView con la tecla de retorno?

En la biblioteca del IB, la introducción nos dice que cuando el volvemos se presiona la tecla, el teclado para UITextView desaparecerá. Pero en realidad el volvemos La clave solo puede actuar como '\ n'.

Puedo agregar un botón y usar [txtView resignFirstResponder] para ocultar el teclado.

Pero, ¿hay alguna forma de agregar la acción para el volvemos Teclee el teclado para que no necesite agregar UIButton?

preguntado el 31 de marzo de 09 a las 22:03

Siga las instrucciones de esta publicación de blog: iphonedevelopertips.com/cocoa/… -

30 Respuestas

UITextView no tiene ningún método que se llamará cuando el usuario presione la tecla de retorno. Si desea que el usuario pueda agregar solo una línea de texto, use un UITextField. Golpear el retorno y ocultar el teclado por un UITextView no sigue las pautas de la interfaz.

Incluso entonces, si desea hacer esto, implemente el textView:shouldChangeTextInRange:replacementText: método de UITextViewDelegate y en eso verifique si el texto de reemplazo es \n, oculta el teclado.

Puede haber otras formas, pero no conozco ninguna.

Respondido el 12 de enero de 13 a las 06:01

Gracias y el método funciona bien. La razón para usar UITextView es que puede contener texto en varias líneas. Y ahora lo estoy usando como un cuadro de mensaje. - Frío Zhong

Es bastante fácil cambiar la tecla de retorno a "hecho" usando [textField setReturnKeyType: UIReturnKeyDone]; o usando el constructor de interfaces - casebash

Bien, ahora entiendo que la forma de Apple de terminar con un campo de texto de varias líneas es agregar hecho a la barra de menú: casebash

Esta no es una buena manera de resolver esto porque está restringiendo al usuario para que use Intro para salir del teclado. Probablemente la mejor manera es agregar un botón que ejecute el método resignFirstResponder. - Ele

@Casebash. Parece que establecer la tecla de retorno en "hecho" no resuelve el problema en Xcode 6.4, Swift 2.0. Configuré la clave usando IB. - Desarrollador MB_iOS

Pensé que publicaría el fragmento aquí mismo:

Asegúrese de declarar su apoyo a la UITextViewDelegate protocolo.

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

    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}

Actualización de Swift 4.0:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}

Respondido el 12 de diciembre de 17 a las 15:12

El problema es que esta no es realmente una forma de detectar que el usuario ha tocado la devolución clave. El usuario puede pastas un carácter de retorno en el campo de texto y obtendría el mismo mensaje de delegado. Básicamente, estás haciendo un mal uso de la vista de texto. La forma de descartar el teclado es (1) no hacerlo en absoluto (como cuando redacta un mensaje en la aplicación Correo) o (2) tener un botón Listo en otra parte de la interfaz (como en la aplicación Notas). Por ejemplo, puede adjuntar un botón como vista de accesorio al teclado. - mate

@ Sam V ese fragmento fue genial. esto funciona para mi. muchas gracias hombre. ¿Hay algún fragmento para descartar el teclado numérico? saludos shishir - shishir.bobby

Magnífico. Solo un recordatorio de que, en algunas situaciones, para deshacerse del teclado, intente seguir las líneas ... [self.view endEditing: YES]; - gordito

@Vojto, funciona bien en iPad. Probablemente no haya configurado el delegado. - Vincent

El problema es que el teclado puede estar ocultando parte de la interfaz que se usa para cerrar. Es realmente absurdo que IOS no tenga un botón en cada teclado dedicado a cerrar el teclado para que el usuario pueda hacerlo si lo desea. - Sani Elfishawy

Sé que esto ya ha sido respondido, pero realmente no me gusta usar el literal de cadena para la nueva línea, así que esto es lo que hice.

- (BOOL)textView:(UITextView *)txtView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if( [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound ) {
        return YES;
    }

    [txtView resignFirstResponder];
    return NO;
}

Actualización de Swift 4.0:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text as NSString).rangeOfCharacter(from: CharacterSet.newlines).location == NSNotFound {
    return true
}
txtView.resignFirstResponder()
return false
}

respondido 20 nov., 17:04

Podría modificarlo así: NSRange resultRange = [text rangeOfCharacterFromSet: [NSCharacterSet newlineCharacterSet] opciones: NSBackwardsSearch]; Debido a que esto es un truco de todos modos, parece que verificar el final de la cadena para un retorno podría ser una ruta más segura. - máximo poder

@maxpower Muy buen comentario. Además, es mejor verificar el texto reemplazado, por ejemplo NSString *replacedText = [textView.text stringByReplacingCharactersInRange:range withString:text]. - Rudolf Adamkovic

Imagine a un usuario que pega un texto copiado de otro lugar que contiene una nueva línea. Probablemente se confundirían cuando, en lugar de agregar el texto, la aplicación simplemente descarta el teclado. - Nikolái Ruhe

Sé que esto ha sido respondido muchas veces, pero aquí están mis dos centavos al problema.

Encontré las respuestas por savermette y ribeto realmente útil, y también el comentario de máximo poder en el capítulo respecto a la ribetorespuesta. Pero hay un problema con esos enfoques. El problema que mate menciones en el savermetteLa respuesta es que si el usuario quiere pegar algo con un salto de línea dentro, el teclado se escondería sin pegar nada.

Entonces, mi enfoque es una mezcla de las tres soluciones mencionadas anteriormente y solo verifica si la cadena ingresada es una nueva línea cuando la longitud de la cadena es 1, por lo que nos aseguramos de que el usuario esté escribiendo en lugar de pegar.

Esto es lo que hice:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSRange resultRange = [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet] options:NSBackwardsSearch];
    if ([text length] == 1 && resultRange.location != NSNotFound) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}

contestado el 23 de mayo de 17 a las 13:05

Ésta es la mejor solución para este problema. La respuesta de samvermette no tiene en cuenta la situación en la que el usuario desea pegar un texto. - marcopaivaf

Una forma más elegante es descartar el teclado cuando el usuario toca en algún lugar fuera del marco del teclado.

Primero, configure la vista de su ViewController en la clase "UIControl" en el inspector de identidad en UIBuilder. Mantenga presionada la tecla Control y arrastre la vista al archivo de encabezado de ViewController y vincúlela como una acción con el evento como Touch Up Inside, como por ejemplo:

ViewController.h

-(IBAction)dismissKeyboardOnTap:(id)sender;

En el archivo principal de ViewController, ViewController.m:

-(IBAction)dismissKeyboardOnTap:(id)sender
    {
         [[self view] endEditing:YES];
    }

Puede requerir un toque dos veces o un toque prolongado utilizando técnicas similares. Es posible que deba configurar su ViewController para que sea un UITextViewDelegate y conectar el TextView al ViewController. Este método funciona tanto para UITextView como para UITextField.

Fuente: Big Nerd Ranch

EDITAR: También me gustaría agregar que si está utilizando un UIScrollView, es posible que la técnica anterior no funcione tan fácilmente a través del Interface Builder. En ese caso, puede usar un UIGestureRecognizer y llamar al método [[self view] endEditing: YES] dentro de él. Un ejemplo sería:

-(void)ViewDidLoad{
    ....
    UITapGestureRecognizer *tapRec = [[UITapGestureRecognizer alloc] 
        initWithTarget:self action:@selector(tap:)];
    [self.view addGestureRecognizer: tapRec];
    ....
}

-(void)tap:(UITapGestureRecognizer *)tapRec{
    [[self view] endEditing: YES];
}

Cuando el usuario toca fuera del teclado y no toca un espacio de entrada, el teclado se cerrará.

respondido 24 mar '13, 21:03

Me gusta la idea con GestureRecognizer pero el gran problema es que ya no se puede hacer clic en todos los botones o controles de la vista. - experto

Agregue este método en su controlador de vista.

rápido:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}

Este método también puede resultarle útil:

/**
Dismiss keyboard when tapped outside the keyboard or textView

:param: touches the touches
:param: event   the related event
*/
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if let touch = touches.anyObject() as? UITouch {
        if touch.phase == UITouchPhase.Began {
            textField?.resignFirstResponder()
        }
    }
}

Respondido 30 ago 16, 08:08

No olvides confirmar el protocolo UITextViewDelegate :) - SwiftBoy

No creo que sea una buena idea anular los toques Comenzó y no llamar super.touchesBegan(touches:withEvent:). - TGO

Para expresar la naturaleza simétrica de este código, debe escribir else { return true }. - el significado importa

@ significado-no importa en absoluto - Alejandro Vólkov

@AlexanderVolkov No está de acuerdo en que es una situación simétrica, no sabe a qué me refiero, no cree en el valor del código semánticamente correcto, o ... - el significado importa

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"])
        [textView resignFirstResponder];
    return YES;
}

yourtextView.delegate=self;

También agregue UITextViewDelegate

No olvides confirmar el protocolo

SI no agregaste if([text isEqualToString:@"\n"]) no puedes editar

Respondido 03 Abr '18, 01:04

-1 Esta es solo una versión más pobre de la respuesta de samvermette. Te perdiste regresar NO si el texto es igual a @"\n". - devios1

Hay otra solución mientras se usa con uitextview, puede agregar la barra de herramientas como InputAccessoryView en "textViewShouldBeginEditing", y desde el botón de hecho de esta barra de herramientas puede descartar el teclado, el código para esto es el siguiente:

En viewDidLoad

toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)]; //toolbar is uitoolbar object
toolBar.barStyle = UIBarStyleBlackOpaque;
UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(btnClickedDone:)];
[toolBar setItems:[NSArray arrayWithObject:btnDone]];

En el método textviewdelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
     [textView setInputAccessoryView:toolBar];
     return YES;
}

En la acción del botón Listo, que está en la barra de herramientas, sigue:

-(IBAction)btnClickedDone:(id)sender
{
    [self.view endEditing:YES];
}

Respondido 30 ago 16, 09:08

Encontré la respuesta por josebama para ser la respuesta más completa y limpia disponible en este hilo.

abajo esta el Swift 4 sintaxis para ello:

func textView(_ textView: UITextView, shouldChangeTextIn _: NSRange, replacementText text: String) -> Bool {
    let resultRange = text.rangeOfCharacter(from: CharacterSet.newlines, options: .backwards)
    if text.count == 1 && resultRange != nil {
        textView.resignFirstResponder()
        // Do any additional stuff here
        return false
    }
    return true
}

respondido 12 nov., 18:15

El resultRange tiene como objetivo probar si el texto solo contiene nuevas líneas que eviten el código "\ n". - qinghua

Similar a otras respuestas usando el UITextViewDelegate pero una interfaz rápida más nueva isNewline sería:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if let character = text.first, character.isNewline {
        textView.resignFirstResponder()
        return false
    }
    return true
}

Respondido 30 Abr '20, 17:04

rápido

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
    }
    return true
}

y configurar

Respondido 22 Feb 16, 23:02

¿De dónde es esa captura de pantalla? - Diana

Usando el controlador de navegación para alojar una barra para cerrar el teclado:

en el archivo .h:

UIBarButtonItem* dismissKeyboardButton;

en el archivo .m:

- (void)viewDidLoad {
    dismissKeyboardButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(dismissKeyboard)];
}

-(void)textViewDidBeginEditing:(UITextView *)textView {
    self.navigationItem.rightBarButtonItem = dismissKeyboardButton;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    self.navigationItem.rightBarButtonItem = dismissKeyboardButton;
}

-(void)dismissKeyboard {
    [self.textField resignFirstResponder];
    [self.textView resignFirstResponder];
    //or replace this with your regular right button
    self.navigationItem.rightBarButtonItem = nil;
}

Respondido 03 Abr '18, 01:04

Al igual que Matt le comentó a Samvermette, tampoco me gusta la idea de detectar "\ n". La tecla "return" está ahí por una razón en UITextView, es decir, para ir a la siguiente línea, por supuesto.

En mi opinión, la mejor solución es imitar la aplicación de mensajes de iPhone, que consiste en agregar una barra de herramientas (y un botón) en el teclado.

Obtuve el código de la siguiente publicación de blog:

http://www.iosdevnotes.com/2011/02/iphone-keyboard-toolbar/

Pasos:

-Añadir barra de herramientas a su archivo XIB: establezca la altura en 460

-Añadir elemento de botón de la barra de herramientas (si aún no se ha añadido). Si necesita alinearlo a la derecha, agregue también el elemento del botón de la barra flexible a XIB y mueva el elemento del botón de la barra de herramientas

-Cree una acción que vincule su elemento de botón a resignFirstResponder de la siguiente manera:

- (IBAction)hideKeyboard:(id)sender {
    [yourUITextView resignFirstResponder];
}

-Luego:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    CGRect frame = self.keyboardToolbar.frame;
    frame.origin.y = self.view.frame.size.height - 260.0;
    self.keyboardToolbar.frame = frame;

    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    CGRect frame = self.keyboardToolbar.frame;
    frame.origin.y = self.view.frame.size.height;
    self.keyboardToolbar.frame = frame;

    [UIView commitAnimations];
}

respondido 21 mar '12, 00:03

Fuera de contexto. Si bien su solución es elegante, no responde a la pregunta original: "¿Cómo descartar el teclado para UITextView con la tecla de retorno?". Hay situaciones en las que se emplea UITextView para simular un UITextField de ajuste de palabras, no para ingresar varias líneas. - SwiftArquitecto

Aunque está fuera de tema, es muy útil. También quiero que se ingrese un UITextView con varias líneas y descarte el teclado cuando lo desee. - Yeung

Acabo de resolver este problema de una manera diferente.

  • Crea un botón que se colocará en segundo plano.
  • Desde el Inspector de atributos, cambie el tipo de botón a personalizado y hará que el botón sea transparente.
  • Expanda el botón para cubrir toda la vista y asegúrese de que el botón esté detrás de todos los demás objetos. Una forma sencilla de hacer esto es arrastrar el botón a la parte superior de la vista de lista en la Vista
  • Control, arrastre el botón al viewController.h archivo y cree una acción (Evento enviado: Retocar dentro) como:

    (IBAction)ExitKeyboard:(id)sender;
    
  • In ViewController.m debería verse así:

    (IBAction)ExitKeyboard:(id)sender {
        [self.view endEditing:TRUE];
    }
    
  • Ejecute la aplicación, y cuando haga clic fuera de TextView, el teclado desaparecerá

Respondido 27 Feb 14, 10:02

También debe agregar: - (void) textViewDidEndEditing: (UITextView *) textView {[self.TextView resignFirstResponder]; } - samuray

Agregar un observador en viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(textViewKeyPressed:) name: UITextViewTextDidChangeNotification object: nil];

y luego use el selector para buscar "\ n"

-(void) textViewKeyPressed: (NSNotification*) notification {

  if ([[[notification object] text] hasSuffix:@"\n"])
  {
    [[notification object] resignFirstResponder];
  }
}

Utiliza "\ n" y no busca específicamente una clave de retorno, pero creo que está bien.

ACTUALIZAR

Vea la respuesta de ribto a continuación, que usa [NSCharacterSet newlineCharacterSet] en lugar de \n

Respondido el 26 de enero de 15 a las 18:01

Err, usa \n y la clave de retorno se detecta en función de \n por lo que comprueba la clave de retorno. La única diferencia es que está usando notificaciones en lugar de usar textViewDelegates. - BuenoSp33d

Ahora creo que comprobando [NSCharacterSet newlineCharacterSet] en lugar de \ n podría ser una mejor manera de hacerlo. - toddb

código SWIFT

Implemente UITextViewDelegate en su clase / Vista así:

class MyClass: UITextViewDelegate  { ...

establecer el delegado de textView en uno mismo

myTextView.delegate = self

Y luego implemente lo siguiente:

  func textViewDidChange(_ textView: UITextView) {
    if textView.text.characters.count >= 1 {

        if let lastChar = textView.text.characters.last {

            if(lastChar == "\n"){

              textView.text = textView.text.substring(to: textView.text.index(before: textView.text.endIndex))
              textView.resignFirstResponder()
            }
        }
    }
}

EDITAR Actualicé el código porque nunca es una buena idea cambiar la entrada del usuario en un campo de texto para una solución alternativa y no restablecer el estado después de que se completó el código de pirateo.

Respondido 11 Jul 17, 14:07

Pruebe lo siguiente:

 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [self.view endEditing:YES];
    }

    return YES;

}

Respondido el 09 de enero de 14 a las 09:01

// Puedes usar esto ...

Paso 1. El primer paso es asegurarse de declarar su apoyo a la UITextViewDelegate protocolo. Esto se hace en su archivo de encabezado, como ejemplo aquí está el encabezado llamado

EditorController.h:

@interface EditorController : UIViewController  {
  UITextView *messageTextView;
}

@property (nonatomic, retain) UITextView *messageTextView;

@end

Paso 2. A continuación, deberá registrar el controlador como delegado de UITextView. Continuando con el ejemplo anterior, así es como he inicializado el UITextView EditorController como delegado ...

- (id) init {
    if (self = [super init]) {
        // define the area and location for the UITextView
        CGRect tfFrame = CGRectMake(10, 10, 300, 100);
        messageTextView = [[UITextView alloc] initWithFrame:tfFrame];
        // make sure that it is editable
        messageTextView.editable = YES;

        // add the controller as the delegate
        messageTextView.delegate = self;
    }

Paso 3. Y ahora la última pieza del rompecabezas es actuar en respuesta a la shouldCahngeTextInRange mensaje de la siguiente manera:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range 
  replacementText:(NSString *)text
{
    // Any new character added is passed in as the "text" parameter
    if ([text isEqualToString:@"\n"]) {
        // Be sure to test for equality using the "isEqualToString" message
        [textView resignFirstResponder];

        // Return FALSE so that the final '\n' character doesn't get added
        return FALSE;
    }
    // For any other character return TRUE so that the text gets added to the view
    return TRUE;
}

Respondido el 19 de enero de 15 a las 12:01

También puede ocultar el teclado cuando se toca en la pantalla de visualización:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     UITouch * touch = [touches anyObject];
     if(touch.phase == UITouchPhaseBegan) {
        [txtDetail resignFirstResponder];
      }
 }

Respondido 24 Feb 14, 10:02

En mi humilde opinión, este es un enfoque muy bueno, mucho mejor que con el botón que cubre la vista completa. - Web o código

Respuesta rápida:

override func viewDidLoad() {
    super.viewDidLoad()
    let tapGestureReconizer = UITapGestureRecognizer(target: self, action: "tap:")
    view.addGestureRecognizer(tapGestureReconizer)
}

func tap(sender: UITapGestureRecognizer) {
    view.endEditing(true)
}

Respondido el 15 de junio de 15 a las 03:06

Usé este código para cambiar el respondedor.

 - (BOOL)textView:(UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
    {
        if ([text isEqualToString:@"\n"]) {
            //[textView resignFirstResponder];
            //return YES;
            NSInteger nextTag = textView.tag + 1;
            // Try to find next responder
            UIResponder* nextResponder = [self.view viewWithTag:nextTag];
            if (nextResponder) {
                // Found next responder, so set it.
                [nextResponder becomeFirstResponder];
            } else {
                // Not found, so remove keyboard.
                [textView resignFirstResponder];
            }
            return NO; 


            return NO;
        }
        return YES;

    }

Respondido el 23 de Septiembre de 15 a las 12:09

por qué no usar [self.view endEditing: YES]; ¿¿una vez?? - ajay_nasa

La pregunta pregunta cómo hacerlo con la tecla de retorno, pero creo que esto podría ayudar a alguien con la intención de hacer que el teclado desaparezca al usar UITextView:

private func addToolBarForTextView() {
    let textViewToolbar: UIToolbar = UIToolbar()
    textViewToolbar.barStyle = .default
    textViewToolbar.items = [
        UIBarButtonItem(title: "Cancel", style: .done,
                  target: self, action: #selector(cancelInput)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace,
                  target: self, action: nil),
        UIBarButtonItem(title: "Post Reply", style: .done,
                  target: self, action: #selector(doneInput))
    ]
    textViewToolbar.sizeToFit()
    yourTextView.inputAccessoryView = textViewToolbar
}

@objc func cancelInput() { print("cancel") }
@objc func doneInput() { print("done") }

override func viewDidLoad() {
    super.viewDidLoad()
    addToolBarForTextView()
}

Llame a addToolBarForTextView () en el capítulo respecto a la verDidLoad o algún otro método de ciclo de vida.

Parece que fue la solución perfecta para mí.

Aclamaciones,

Murat

respondido 23 nov., 19:18

Para 2019 ahora copie y pegue, sin errores de sintaxis y nomenclatura actual - gordito

de lejos, la mejor respuesta aquí. Acabo de corregir el error de sintaxis simple, por supuesto, edite como desee. ¡Gracias! - gordito

Está bien. Todos han dado respuestas con trucos, pero creo que la forma correcta de lograrlo es mediante

Conectando la siguiente acción al "Terminó en la salida"evento en Interface Builder. (haga clic derecho en el TextField y cntrl-arrastrar desde 'Terminó en la salida'al siguiente método.

-(IBAction)hideTheKeyboard:(id)sender
{
    [self.view endEditing:TRUE];
}

Respondido 25 Abr '16, 11:04

-1 La pregunta es sobre UITextView y no UITextField mi amigo - Yogui

la mayoría de estas respuestas están aquí con votos porque se adapta a varios escenarios de diferentes desarrolladores. - carbonero

Si está utilizando un UITextField, esta es la forma de hacerlo. Por cierto, debe usar SÍ / NO para los BOOL de Objective-C, no VERDADERO / FALSO. - jon shier

@jshier: VERDADERO / FALSO también está bien - Yogui

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range  replacementText:(NSString *)text
{
    if (range.length==0) {
        if ([text isEqualToString:@"\n"]) {
            [txtView resignFirstResponder];
            if(textView.returnKeyType== UIReturnKeyGo){

                [self PreviewLatter];
                return NO;
            }
            return NO;
        }
    }   return YES;
}

Respondido 27 ago 14, 07:08

+ (void)addDoneButtonToControl:(id)txtFieldOrTextView
{
    if([txtFieldOrTextView isKindOfClass:[UITextField class]])
    {
        txtFieldOrTextView = (UITextField *)txtFieldOrTextView;
    }
    else if([txtFieldOrTextView isKindOfClass:[UITextView class]])
    {
        txtFieldOrTextView = (UITextView *)txtFieldOrTextView;
    }

    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0,
                                                                          0,
                                                                          [Global returnDeviceWidth],
                                                                          50)];
    numberToolbar.barStyle = UIBarStyleDefault;


    UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_return"]
                                                                style:UIBarButtonItemStyleBordered
                                                               target:txtFieldOrTextView
                                                               action:@selector(resignFirstResponder)];

    numberToolbar.items = [NSArray arrayWithObjects:btnDone,nil];
    [numberToolbar sizeToFit];

    if([txtFieldOrTextView isKindOfClass:[UITextField class]])
    {
         ((UITextField *)txtFieldOrTextView).inputAccessoryView = numberToolbar;
    }
    else if([txtFieldOrTextView isKindOfClass:[UITextView class]])
    {
         ((UITextView *)txtFieldOrTextView).inputAccessoryView = numberToolbar;
    }
}

respondido 10 mar '15, 08:03

Deberías agregar UIToolbar a la parte superior de UITextView para facilitar en lugar de usar shouldChangeTextIn

En Swift 4

let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        toolbar.barStyle = .default
        toolbar.items = [
            UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
            UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneAction))
        ]
        textView.inputAccessoryView = toolbar
@objc func doneAction(){
 self.textView.resignFirstResponder()
}

Respondido 25 Feb 19, 10:02

De lejos, la mejor solución. Tenga en cuenta que en lugar de configurar el marco, simplemente use toolbar.sizeToFit() - gordito

Sé que no es la respuesta exacta a esta pregunta, pero encontré este hilo después de buscar en Internet una respuesta. Asumo que otros comparten ese sentimiento.

Esta es mi variación del UITapGestureRecognizer que encuentro confiable y fácil de usar: simplemente configure el delegado de TextView en ViewController.

En lugar de ViewDidLoad, agrego UITapGestureRecognizer cuando TextView se activa para editar:

-(void)textViewDidBeginEditing:(UITextView *)textView{
    _tapRec = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];

    [self.view addGestureRecognizer: _tapRec];
    NSLog(@"TextView Did begin");
}

Cuando toco fuera de TextView, la vista finaliza el modo de edición y UITapGestureRecognizer se elimina a sí mismo para que pueda continuar interactuando con otros controles en la vista.

-(void)tap:(UITapGestureRecognizer *)tapRec{
    [[self view] endEditing: YES];
    [self.view removeGestureRecognizer:tapRec];
    NSLog(@"Tap recognized, tapRec getting removed");
}

Espero que esto ayude. Parece tan obvio, pero nunca he visto esta solución en ninguna parte de la web, ¿estoy haciendo algo mal?

Respondido 13 Oct 13, 22:10

No olvide configurar el delegado para textView; de lo contrario, resignfirstresponder no funcionará.

contestado el 20 de mayo de 14 a las 07:05

Prueba esto .

NSInteger lengthOfText = [[textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length];

respondido 31 mar '15, 10:03

Para Xcode 6.4., Swift 1.2. :

   override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)
    {
        super.touchesBegan(touches, withEvent: event)
        if let touch = touches.first as? UITouch
        {
            self.meaningTextview.resignFirstResponder()
        }
    }

Respondido 09 Jul 15, 10:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.