iphone objective-c cocoa-touch uikit uitextview

iphone - uitextfield



Ocultar el teclado al perder el foco en una UITextView (10)

Así que tengo una UITextView que estoy usando para permitir que el usuario envíe algún texto.

Mi problema es que parece que no puedo entender cómo permitir que el usuario ''Cancele'' tocando fuera de UITextView.


override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { var touch = event.allTouches()?.anyObject() as UITouch if( textfield.isFirstResponder() && touch.view != textfield) { textfield.resignFirstResponder() NSLog("Resigning first responder since touches began outside") } super.touchesBegan(touches, withEvent: event) }

La respuesta de Ohhorob también funcionó para mí. Aquí está el equivalente rápido simple.


Otro enfoque que utilicé mucho cuando trabajo con UITableViews, la barra de búsqueda y el teclado es esto, creo que puede aplicarlo al campo de texto

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)]; [self.tableView addGestureRecognizer:gestureRecognizer]; gestureRecognizer.cancelsTouchesInView = NO; // this prevents the gesture recognizers to ''block'' touches [gestureRecognizer release];

Y luego, aquí está la función de devolución de llamada simple

- (void)hideKeyboard { [myTextField resignFirstResponder]; }

Espero eso ayude


En mi vista:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; // pass touches up to viewController [self.nextResponder touchesBegan:touches withEvent:event]; }

En mi viewcontroller:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; if (keyboardShown && [touch view] != self.TextView) { [self.TextView resignFirstResponder]; } [super touchesBegan:touches withEvent:event]; } - (void)keyboardWasShown:(NSNotification*)aNotification { keyboardShown = YES; }


Quería una versión de esto que funcionara para renunciar desde cualquier punto de vista, sin requerir puntos de venta específicos para cada uno. Aquí está mi solución, que pongo en una de mis vistas de contenedor estándar.

Está usando MonoTouch C #, aunque debería ser obvio cómo convertirlo a Objective-C

private void findAndResignFirstResponder(UIView node=null) { if (node == null) { return; } if (node.IsFirstResponder) { node.ResignFirstResponder(); return; } foreach (UIView view in node.Subviews) { findAndResignFirstResponder(node:view); } } private bool haveDrag = false; public override void TouchesEnded(NSSet touches, UIEvent evt) { if (!haveDrag) { UITouch touch = (UITouch)evt.AllTouches.AnyObject; if (!touch.View.CanBecomeFirstResponder) { this.findAndResignFirstResponder(this); Console.WriteLine("resign"); } } base.TouchesEnded (touches, evt); } public override void TouchesMoved(NSSet touches, UIEvent evt) { haveDrag = true; base.TouchesMoved (touches, evt); } public override void TouchesBegan(NSSet touches, UIEvent evt) { haveDrag = false; base.TouchesBegan (touches, evt); }


Aquí hay una solución mejor que no depende de una toma de corriente y que funcionará con cualquier cantidad de objetos UITextField en su controlador.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; if (![[touch view] isKindOfClass:[UITextField class]]) { [self.view endEditing:YES]; } [super touchesBegan:touches withEvent:event]; }


Mi manera de hacerlo ...

  • Agregue una referencia al TextView en la interfaz @ de su ViewController:

    @property (weak, nonatomic) IBOutlet UITextView *yourTextView;

  • Anule este método en @implementation de su ViewController:

    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { if ([self.yourTextView isFirstResponder]) { [self.yourTextView resignFirstResponder]; } }


Muy fácil

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.view endEditing:YES]; }


Esta es una publicación anterior, pero estaba implementando esta solución cuando encontré algo mucho más simple (tal vez no estaba disponible en ese momento).

[self.myTextView endEditing: YES];

Estoy usando una UITableView, así que puse esta línea en el método didSelectRowAtIndexPath: Hasta aquí todo bien...


Aquí está el código rápido 3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { if textField.isFirstResponder && touch.view != textField { textField.resignFirstResponder() } } super.touchesBegan(touches, with: event) }


Simplificando la respuesta de tuzzolotron : Donde el siguiente enchufe está conectado correctamente en tu xib

IBOutlet UITextView *myTextView;

Use esto en el controlador de vista:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; if ([myTextView isFirstResponder] && [touch view] != myTextView) { [myTextView resignFirstResponder]; } [super touchesBegan:touches withEvent:event]; }

Un toque en la Vista del Controlador de Vista, fuera de la Vista de Texto, resignará al primer respondedor, cerrando el teclado.