2012-07-19 16 views
74

Tengo un botón y campo de texto de texto en mi opinión. cuando hago clic en el campo de texto aparece un teclado y puedo escribir en el campo de texto y yo también capaz de ocultar el teclado haciendo clic en el botón añadiendo:cómo agregar una acción en la tecla de retorno UITextField?

[self.inputText resignFirstResponder]; 

Ahora desea habilitar tecla de retorno del teclado. cuando presione el teclado desaparecerá y algo sucederá. ¿Cómo puedo hacer esto?

+1

Posible duplicado: http://stackoverflow.com/questions/4761648/close-the-keyboard-on-uitextfield – wquist

Respuesta

150

garantizar la "auto" se suscribe a UITextFieldDelegate e inicializa inputText con:

self.inputText.delegate = self; 

Agregue el método siguiente a la "libre":

- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
    if (textField == self.inputText) { 
     [textField resignFirstResponder]; 
     return NO; 
    } 
    return YES; 
} 

O en Swift:

func textFieldShouldReturn(textField: UITextField) -> Bool { 
    if textField == inputText { 
     textField.resignFirstResponder() 
     return false 
    } 
    return true 
} 
4

Con estilo de extensión en swift 3.0

Primero, configure delegado para su campo de texto.

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.inputText.delegate = self 
} 

A continuación, se ajustan a UITextFieldDelegate en la extensión de su controlador de vista

extension YourViewController: UITextFieldDelegate { 
    func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
     if textField == inputText { 
      textField.resignFirstResponder() 
      return false 
     } 
     return true 
    } 
} 
Cuestiones relacionadas