2009-09-21 23 views

Respuesta

107

Simplificar tuzzolotron's answer: Donde la siguiente salida está conectada correctamente en su xib

IBOutlet UITextView *myTextView; 

Uso 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, fuera de la vista de texto, resignará al primer respondedor, cerrando el teclado.

+1

¡Gran solución! – DeZigny

+0

Estaré encantado de ayudar al infractor si esto no funciona para ellos ... simplemente deje un comentario o comience una nueva pregunta y conéctela aquí. – ohhorob

+6

ohhorob, esta solución no funciona si hacemos clic en otra salida a la vista, ¿me pueden ayudar con eso? – TilalHusain

7

En mi punto de 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; 
} 
+0

hace este trabajo, o se nos pide que mirar el código? – Garrett

+0

Esta es la solución que implementé. Funciona. – tuzzolotron

+1

¿Cómo agrego el método touchesBegan a UITableView que he hecho una subvista de self.view del UIViewController en el que estoy trabajando? ¿Debo hacer una subclase de UITableView, es decir, @interface TouchableTableView: UITableView? ¿O existe una manera más fácil de hacerlo sin subclasificar UITableView? – ma11hew28

30

Otro enfoque utilicé mucho cuando se trabaja con UITableViews, Searchbar y el teclado está presente, creo que se puede aplicar a 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 entonces, aquí está la sencilla función de devolución de llamada

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

Espero que ayude

+2

Puede agregar a [vista propia] si está trabajando con un ViewController. –

+0

no, no funcionará, la vista de tablas y pergaminos tiene sus propias interacciones – Softlion

+0

Esta respuesta es la mejor. También funciona para un grupo de campos de texto en un scrollView cuando agrego tapGestureRecognizer a self.view –

0

Quería una versión de esto que funcionara para renunciar a cualquier vista, sin requerir salidas específicas para cada una. Aquí está mi solución, que puse en uno de mis puntos de vista estándar de contenedores ..

Se trata de utilizar MonoTouch C#, aunque debería ser obvio cómo convertir 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); 
    } 
1

que aquí hay una solución mejor que no depende en una toma de corriente y va a 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]; 
} 
+0

no Creo que necesita comprobar UITextField - incluso si 'endEditing:' indiscriminadamente, cambiar entre campos de texto sigue funcionando, el teclado permanece activo –

0

Mi manera de hacerlo ...

  • añadir una referencia a la Vista de Texto en el @interface de su ViewController:

    @property (weak, nonatomic) IBOutlet UITextView *yourTextView; 
    
  • reemplazar este método en el @ implementación de su ViewController:

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

Muy fácil

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

Ésta es una entrada antigua, pero yo estaba poniendo en práctica esta solución cuando me encontré algo mucho más simple (tal vez no estaba disponible en ese entonces).

[self.myTextView endEditing: YES];

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

1
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) 
} 

respuesta de ohhorob trabajó para mí también. Aquí está el equivalente rápido simple.

1

Aquí está el código SWIFT 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) 
} 
Cuestiones relacionadas