iOS-Dismiss teclado al tocar fuera de UITextField


Me pregunto cómo hacer que el teclado desaparezca cuando el usuario toca fuera de un UITextField.

Author: Tamás Sengel, 2011-03-15

30 answers

Tendrá que agregar un UITapGestureRecogniser y asignarlo a la vista, y luego llamar al primer respondedor de renuncia en el UITextField en su selector.

El código:

En viewDidLoad

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];

[self.view addGestureRecognizer:tap];

En dismissKeyboard:

-(void)dismissKeyboard 
{
    [aTextField resignFirstResponder];
}

(Donde aTextField es el campo de texto responsable del teclado)

Swift 3 la versión se ve así

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)

For dismissKeyboard

func dismissKeyboard (_ sender: UITapGestureRecognizer) {
    aTextField.resignFirstResponder()
}
 720
Author: Jensen2k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-16 07:29:49

Hice un puré de algunas respuestas.

Use un ivar que se inicialice durante viewDidLoad:

UIGestureRecognizer *tapper;

- (void)viewDidLoad
{
    [super viewDidLoad];
    tapper = [[UITapGestureRecognizer alloc]
                initWithTarget:self action:@selector(handleSingleTap:)];
    tapper.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapper];
}

Descartar lo que está editando actualmente:

- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
    [self.view endEditing:YES];
}
 168
Author: drewish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-07 18:42:49

Marque esto, esta sería la forma más fácil de hacerlo,

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
      [self.view endEditing:YES];// this will do the trick
}

O

Esta biblioteca manejará incluyendo el desplazamiento automático de la barra de desplazamiento, toque el espacio para ocultar el teclado, etc...

Https://github.com/michaeltyson/TPKeyboardAvoiding

 100
Author: Prasad De Zoysa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-20 05:38:16

Veo que algunas personas están teniendo problemas usando el método UITapGestureRecognizer. La forma más fácil de lograr esta funcionalidad sin dejar intacto el comportamiento de toque de mi botón existente es agregar solo una línea a la respuesta de @Jensen2k:

[tap setCancelsTouchesInView:NO];

Esto permitió que mis botones existentes siguieran funcionando sin usar el método de @Dmitry Sitnikov.

Lea sobre eso property aquí (buscar CancelsTouchesInView): Referencia de la clase UIGestureRecognizer

No estoy seguro de cómo funcionaría con barras de desplazamiento, como veo algunos tenían problemas con, pero con suerte alguien más podría ejecutar en el mismo escenario que tenía.

 82
Author: Qiao Yi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-23 09:32:26

Es mejor hacer que su UIView sea una instancia de UIControl (en interface builder) y luego conectar su evento TouchUpInside al método dismissKeyboard. Este método IBAction se verá como:

- (IBAction)dismissKeyboard:(id)sender {
    [aTextBox resignFirstResponder];
}
 55
Author: Dmitry Sitnikov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-23 08:57:11

Versión Swift, esto funciona en combinación con otros elementos (como un UIButton u otro UITextField):

override func viewDidLoad() {
    super.viewDidLoad()

    let tapper = UITapGestureRecognizer(target: self, action:#selector(endEditing))
    tapper.cancelsTouchesInView = false
    view.addGestureRecognizer(tapper)
}
 25
Author: Rob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-02 09:54:06

Qué tal esto: Sé que este es un post antiguo. Podría ayudar a alguien:)

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {  
    NSArray *subviews = [self.view subviews];
    for (id objects in subviews) {
        if ([objects isKindOfClass:[UITextField class]]) {
            UITextField *theTextField = objects;
            if ([objects isFirstResponder]) {
                [theTextField resignFirstResponder];
            }
        } 
    }
}
 15
Author: Mr H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-26 08:14:05

Esta es una buena solución genérica:

Objetivo-C:

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

Swift:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

Basado en la solución de @icodebuster: https://stackoverflow.com/a/18756253/417652

 13
Author: eduludi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:26

Creo que la forma más fácil (y mejor) de hacer esto es subclasificar su vista global y usar el método hitTest:withEvent para escuchar cualquier toque. Los toques en el teclado no están registrados, por lo que hitTest:withEvent solo se llama cuando toca/desplaza/desliza/pellizca... en otro lugar, luego llame a [self endEditing:YES].

Esto es mejor que usar touchesBegan porque touchesBegan no se llaman si hace clic en un botón en la parte superior de la vista. Es mejor que UITapGestureRecognizer que no puede reconocer un gesto de desplazamiento, por ejemplo. También es mejor que usar una pantalla tenue porque en una interfaz de usuario compleja y dinámica, no se puede poner una pantalla tenue en todas partes. Además, no bloquea otras acciones, no es necesario tocar dos veces para seleccionar un botón externo (como en el caso de un UIPopover).

Además, es mejor que llamar a [textField resignFirstResponder], porque puede tener muchos campos de texto en la pantalla, por lo que esto funciona para todos ellos.

 10
Author: Enzo Tran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-01 07:24:00

Swift 4

Configure su UIViewController con este método de extensión una vez, por ejemplo, en viewDidLoad:

override func viewDidLoad() {
    super.viewDidLoad()
    self.setupHideKeyboardOnTap()
}

Y el teclado será despedido incluso pulsando sobre el NavigationBar.

import UIKit
extension UIViewController {
    /// Call this once to dismiss open keyboards by tapping anywhere in the view controller
    func setupHideKeyboardOnTap() {
        self.view.addGestureRecognizer(self.endEditingRecognizer())
        self.navigationController?.navigationBar.addGestureRecognizer(self.endEditingRecognizer())
    }

    /// Dismisses the keyboard from self.view
    private func endEditingRecognizer() -> UIGestureRecognizer {
        let tap = UITapGestureRecognizer(target: self.view, action: #selector(self.view.endEditing(_:)))
        tap.cancelsTouchesInView = false
        return tap
    }
}
 8
Author: FBente,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-26 13:09:04

Puede hacer esto usando el Storyboard en XCode 6 y superior:


Crear la acción para ocultar el teclado

Agregue esto al archivo de encabezado de la clase utilizada por su ViewController:

@interface TimeDelayViewController : UIViewController <UITextFieldDelegate>

- (IBAction)dissmissKeyboardOnTap:(id)sender;

@end

Luego agregue esto al archivo de implementación del mismo ViewController:

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

Esta será ahora una de las' Acciones recibidas ' para su escena de storyboard (es decir, ViewController):

introduzca la descripción de la imagen aquí


Conectar la acción a la evento de usuario

Ahora necesita conectar esta acción al gesto del usuario de tocar el teclado.

Importante: Debe convertir el 'UIView' que está contenido en su storyboard a un UIControl, para que pueda recibir eventos. Seleccione la vista desde la jerarquía de escenas del Controlador de vista:

introduzca la descripción de la imagen aquí

...y cambiar su clase:

introduzca la descripción de la imagen aquí

Ahora arrastre desde el pequeño círculo junto a la 'acción recibida' para su escena, en una parte ' vacía 'de tu escena (en realidad estás arrastrando la' Acción recibida ' al UIControl). Se te mostrará una selección de eventos a los que puedes conectar tu acción:

introduzca la descripción de la imagen aquí

Seleccione la opción' retocar dentro'. Ahora has enganchado la IBAction que creaste a una acción del usuario de tocar el teclado. Cuando el usuario toque el teclado, ahora estará oculto.

(NOTA: Para enganchar la acción al evento, también puede arrastrar desde el recibido acción directamente en el UIControl en su jerarquía de Controladores de vista. Se muestra como 'Control' en la jerarquía.)

 6
Author: Chris Halcrow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-16 01:47:40

Esta debe ser la forma más fácil de ocultar el teclado tocando fuera:

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

(desde ¿Cómo descartar el teclado cuando el usuario toca otra área fuera de textfield?)

 6
Author: Maggie Phillips,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:38

Si te he acertado, quieres renunciar al teclado tocando fuera de textfield pero no tienes referencia de tu textfield.

Prueba esto;

  • Tome el campo de texto global, llamémoslo reftextField
  • Ahora en textFieldDidBeginEditing establezca el campo de texto referenciado en

    - (void) textFieldDidBeginEditing:(UITextField *)textField{
        reftextField = textField;
    }
    
  • Ahora puede usar felizmente en cualquier reloj de botón, (agregar un botón transparente al comenzar a editar recomendado)

    - (void)dismissKeyboard {
          [reftextField resignFirstResponder];
    }
    
  • O para renunciar botón hecho tratar este.

    //for resigning on done button    
    - (BOOL) textFieldShouldReturn:(UITextField *)textField{
        [textField resignFirstResponder];
        return YES;
    }
    
 5
Author: rptwsthi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-01 14:51:31

Si la vista está incrustada en un UIScrollView, puede usar lo siguiente:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

El primero animará el teclado fuera de la pantalla cuando se desplace la vista de tabla y el último ocultará el teclado como la aplicación stock Messages.

Tenga en cuenta que estos están disponibles en iOS 7.0 o superior.

 4
Author: Joe Masilotti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-14 13:11:53

Solo para agregar a la lista aquí mi versión de cómo descartar un teclado en outside touch.

ViewDidLoad:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleTap];

En cualquier lugar:

-(void)handleSingleTap:(UITapGestureRecognizer *)sender{
    [textFieldName resignFirstResponder];
    puts("Dismissed the keyboard");
}
 3
Author: John Riselvato,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-17 00:50:28

Muchas respuestas excelentes aquí sobre el uso de UITapGestureRecognizer all todas las cuales rompen el botón clear (X) de UITextField. La solución es suprimir el reconocedor de gestos a través de su delegado:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    BOOL touchViewIsButton = [touch.view isKindOfClass:[UIButton class]];
    BOOL touchSuperviewIsTextField = [[touch.view superview] isKindOfClass:[UITextField class]];
    return !(touchViewIsButton && touchSuperviewIsTextField);
}

No es la solución más robusta, pero funciona para mí.

 3
Author: skedastik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-22 03:59:57

Puede crear una categoría para UIView y anular el método touchesBegan de la siguiente manera.

Está funcionando bien para mí.Y es centralizar la solución para este problema.

#import "UIView+Keyboard.h"
@implementation UIView(Keyboard)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.window endEditing:true];
    [super touchesBegan:touches withEvent:event];
}
@end
 3
Author: Hiren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-29 09:12:52

Versión rápida de la respuesta de @Jensen2k:

let gestureRecognizer : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: "dismissKeyboard")
self.view.addGestureRecognizer(gestureRecognizer)

func dismissKeyboard() {
    aTextField.resignFirstResponder()
}

Un revestimiento

self.view.addTapGesture(UITapGestureRecognizer.init(target: self, action: "endEditing:"))
 3
Author: Syed Asad Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-17 05:38:47

Utilicé el ejemplo de Barry para mi nuevo desarrollo. Funcionó muy bien! pero tuve que incluir un ligero cambio, requerido para descartar el teclado solo para el campo de texto que se está editando.

Por lo tanto, he añadido a Barry ejemplo lo siguiente:

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    _textBeingEdited = textField;
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
    _textBeingEdited = nil;
}

Además, cambié el método hideKeyboard de la siguiente manera:

- (IBAction)hideKeyboard:(id)sender
{
    // Just call resignFirstResponder on all UITextFields and UITextViews in this VC
    // Why? Because it works and checking which one was last active gets messy.
    //UITextField * tf = (UITextField *) sender;
    [_textBeingEdited resignFirstResponder];
}
 2
Author: mtorre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-18 23:01:45

Una de las formas más fáciles y cortas es agregar este código a su viewDidLoad

[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc]
                                     initWithTarget:self.view
                                     action:@selector(endEditing:)]];
 2
Author: Sudhin Davis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-07 07:45:43

Swift 4 oneliner

view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:))))
 2
Author: newDeveloper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-01 03:13:53

Enviar mensaje resignFirstResponder al textfiled que lo puso allí. Por favor vea este post para más información.

 1
Author: Ke Sun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:44

Esto funciona

En este ejemplo, aTextField es el único UITextField.... Si hay otros o UITextViews, hay un poco más que hacer.

// YourViewController.h
// ...
@interface YourViewController : UIViewController /* some subclass of UIViewController */ <UITextFieldDelegate> // <-- add this protocol
// ...
@end

// YourViewController.m

@interface YourViewController ()
@property (nonatomic, strong, readonly) UITapGestureRecognizer *singleTapRecognizer;
@end
// ...

@implementation
@synthesize singleTapRecognizer = _singleTapRecognizer;
// ...

- (void)viewDidLoad
{
    [super viewDidLoad];
    // your other init code here
    [self.view addGestureRecognizer:self.singleTapRecognizer];

{

- (UITapGestureRecognizer *)singleTapRecognizer
{
    if (nil == _singleTapRecognizer) {
        _singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapToDismissKeyboard:)];
        _singleTapRecognizer.cancelsTouchesInView = NO; // absolutely required, otherwise "tap" eats events.
    }
    return _singleTapRecognizer;
}

// Something inside this VC's view was tapped (except the navbar/toolbar)
- (void)singleTapToDismissKeyboard:(UITapGestureRecognizer *)sender
{
    NSLog(@"singleTap");
    [self hideKeyboard:sender];
}

// When the "Return" key is pressed on the on-screen keyboard, hide the keyboard.
// for protocol UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    NSLog(@"Return pressed");
    [self hideKeyboard:textField];
    return YES;
}

- (IBAction)hideKeyboard:(id)sender
{
    // Just call resignFirstResponder on all UITextFields and UITextViews in this VC
    // Why? Because it works and checking which one was last active gets messy.
    [aTextField resignFirstResponder];
    NSLog(@"keyboard hidden");
}
 1
Author: Barry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-11 11:55:50

Probé muchas de las respuestas aquí y no tuve suerte. Mi reconocedor de gestos tap siempre estaba causando que mis UIButtons no respondieran cuando se tocaba, incluso cuando establecí la propiedad cancelsTouchesInView del reconocedor de gestos en NO.

Esto es lo que finalmente resolvió el problema:

Tener un ivar:

UITapGestureRecognizer *_keyboardDismissGestureRecognizer;

Cuando un campo de texto comienza a editarse, establezca el reconocedor de gestos:

- (void) textFieldDidBeginEditing:(UITextField *)textField
{
    if(_keyboardDismissGestureRecognizer == nil)
    {
        _keyboardDismissGestureRecognizer = [[[UITapGestureRecognizer alloc]
                                       initWithTarget:self
                                       action:@selector(dismissKeyboard)] autorelease];
        _keyboardDismissGestureRecognizer.cancelsTouchesInView = NO;

        [self.view addGestureRecognizer:_keyboardDismissGestureRecognizer];
    }
}

Entonces el truco está en cómo configurar el método dismissKeyboard:

- (void) dismissKeyboard
{
    [self performSelector:@selector(dismissKeyboardSelector) withObject:nil afterDelay:0.01];
}

- (void) dismissKeyboardSelector
{
    [self.view endEditing:YES];

    [self.view removeGestureRecognizer:_keyboardDismissGestureRecognizer];
    _keyboardDismissGestureRecognizer = nil;
}

Supongo solo hay algo acerca de obtener la ejecución de dismissKeyboardSelector de la pila de ejecución de manejo táctil...

 1
Author: user1021430,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-14 21:07:33
- (void)viewDidLoad
{
    [super viewDidLoad]; 

UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]
                                                          initWithTarget:self
                                                          action:@selector(handleSingleTap:)];
    [singleTapGestureRecognizer setNumberOfTapsRequired:1];
    [singleTapGestureRecognizer requireGestureRecognizerToFail:singleTapGestureRecognizer];

    [self.view addGestureRecognizer:singleTapGestureRecognizer];
}

- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
    [self.view endEditing:YES];
    [textField resignFirstResponder];
    [scrollView setContentOffset:CGPointMake(0, -40) animated:YES];

}
 1
Author: Gaurav Gilani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-19 07:01:41

Agregue este código en su ViewController.m archivo:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
 1
Author: aashish tamsya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-17 11:35:02
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if let touch = touches.first{
     view.endEditing(true)

     }
}
 1
Author: Phani Sai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-12 06:10:12

En este caso, se puede usar ScrollView y agregar a TextField en ScrollView y quiero tocar el ScrollView y Ver luego Descartar el Teclado. Intenté crear un código de ejemplo por si acaso. Así,

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tap(_:)))
        view.addGestureRecognizer(tapGesture)
        // Do any additional setup after loading the view, typically from a nib.
    }
    func tap(gesture: UITapGestureRecognizer) {
        textField.resignFirstResponder()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Su Storyboard Mira eso al igual que.

introduzca la descripción de la imagen aquí

 1
Author: Ravi Dhorajiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-04 14:16:58

Puede usar el método UITapGestureRecongnizer para descartar el teclado haciendo clic fuera de UITextField. Mediante el uso de este método cada vez que el usuario haga clic fuera de UITextField entonces teclado obtendrá despedir. A continuación se muestra el fragmento de código para usarlo.

 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissk)];

    [self.view addGestureRecognizer:tap];


//Method
- (void) dismissk
{
    [abctextfield resignFirstResponder];
    [deftextfield resignFirstResponder];

}
 1
Author: Nirzar Gandhi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-16 09:58:53
  • Establecer el delegado de campos de texto en la vista cargó:

    override func viewDidLoad() 
    {
      super.viewDidLoad()
      self.userText.delegate = self
    }
    
  • Agregue esta función:

    func textFieldShouldReturn(userText: UITextField!) -> Bool 
    {
     userText.resignFirstResponder()
     return true;
    }
    
 1
Author: seggy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-06 11:06:18