2012-04-28 18 views
59

Estoy tratando de mostrar los cambios realizados en un UITextField en un UILabel por separado. ¿Hay alguna forma de capturar el texto completo del UITextField después de cada carácter que escribe el usuario? Actualmente estoy usando este método, pero no captura el último carácter que el usuario ha ingresado.iPhone ¿cómo obtener texto de UITextField mientras tipea?

Sé que UITextView tiene el método "didChange", pero no pude encontrar ese método para UITextField.

//does not capture the last character 

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 

     [self updateTextLabelsWithText: textField.text]; 

    return YES; 
} 

¿Cómo puedo tomar el texto de UITextField después de cada carácter introducido?

¡Gracias!

+0

la salida: http://stackoverflow.com/questions/388237/getting-the-value-of-a-uitextfield-as-keystrokes-are-entered – hanumanDev

Respuesta

134
  1. Primero agregue UITextField y UILabel al guión gráfico/plumín
  2. Ahora asigne IBOutlet para UILabel (Aquí he utilizado myLabel)
  3. UITextFieldDelegate Asignar a presentar propietario, también poner en práctica el mismo delegado en .h el archivo
  4. Utilice estas líneas de código:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
    { 
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
        [self updateTextLabelsWithText: newString]; 
    
        return YES; 
    } 
    
    -(void)updateTextLabelsWithText:(NSString *)string 
    { 
        [myLabel setText:string]; 
    } 
    

Espero que esto ayude.

+0

Hummmmm Eso es muy bonito Thx. ..... :) –

+0

Funciona para mí .... –

+0

si elimino el personaje uno por uno. este método no llama al –

67

simplemente manejar la "Edición Changed" evento

[textField addTarget:self 
       action:@selector(editingChanged:) 
    forControlEvents:UIControlEventEditingChanged]; 

y el selector:

-(void) editingChanged:(id)sender { 
    // your code 
} 

Usted puede hacer esto manualmente, o con el guión gráfico por CTRL-arrastrar la "Edición cambiado" Enviado evento a su .h, creando el método editingChanged para usted.

+3

¡su solución es perfecta! gracias – SpaceDog

+10

Esta es en realidad una mejor solución que la aceptada. ¡Gracias!. La respuesta aceptada no borrará completamente el texto de la etiqueta cuando elimine el último carácter de su campo de texto. – Menno

+0

esto se debe seleccionar como respuesta – Lucas

5

En Swift 2.0+

class CheckInViewController: UIViewController, UITextFieldDelegate { 

override func viewDidLoad() { 
    super.viewDidLoad() 

    yourTextField.delegate = self 

} 

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { 
    var updatedTextString : NSString = textField.text as NSString 
    updatedTextString = updatedTextString.stringByReplacingCharactersInRange(range, withString: string) 

    self.methodYouWantToCallWithUpdatedString(updatedTextString) 
    return true 
} 

} 

espero que le ayuda a pioneros rápidas

3

Swift con addTarget Swift 2.0+

titleTextField.addTarget(self, action: #selector(textFieldTyping), forControlEvents: .EditingChanged) 

e implementar selector

func textFieldTyping(textField:UITextField) 
{ 
    //Typing 
} 
1

En Swift 3.0:

Algunas de estas soluciones eran un carácter atrás, o para versiones anteriores de Swift y Obj-C. Esto es lo que estoy usando para Swift 3.0

En la clase, declare un marcador de posición para almacenar el texto.

var tempName = "" 

En viewDidLoad utilicé:

nameField.addTarget(self, action: #selector(typingName), for: .editingChanged) 

Entonces hice una función llamada:

func typingName(textField:UITextField){ 

     if let typedText = textField.text { 
      tempName = typedText 
      print(tempName) 
     } 
    } 
0

Swift 3.0+: Esto funcionó muy bien para mí.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
    self.yourLabel.text = "\(textField.text ?? "")\(string)" 
    return true 
} 
0
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
     if textField == yourTextFieldOutletName 
     { 
      if yourTextFieldOutletName.isEmpty == false 
      { 
      youtlabelname.text = yourTextFieldOutletName.text! 
      } 


     } 

     return true 

    } 

func textViewDidEndEditing(_ textView: UITextView) { 
     if textField == yourTextFieldOutletName 
      { 
       if yourTextFieldOutletName.isEmpty == false 
       { 
       youtlabelname.text = yourTextFieldOutletName.text! 
       } 


      } 
    } 
Cuestiones relacionadas