Buscar..


UITextField - Restringir el campo de texto a ciertos caracteres

Si desea realizar una validación de entrada de usuario de su campo de texto, use el siguiente fragmento de código:

// MARK: - UITextFieldDelegate

let allowedCharacters = CharacterSet(charactersIn:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz").inverted    

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
    let components = string.components(separatedBy: allowedCharacters)
    let filtered = components.joined(separator: "")
    
    if string == filtered {
        
        return true

    } else {
        
        return false
    }
}

C objetivo

#define ACCEPTABLE_CHARACTERS @"0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  
{
      NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARACTERS] invertedSet];

      NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

      return [string isEqualToString:filtered];
}

Además, también puede utilizar los conjuntos de caracteres proporcionados por Apple para realizar la validación:

Echa un vistazo a https://developer.apple.com/reference/foundation/nscharacterset

let allowedCharacters = CharacterSet.alphanumerics.inverted
let allowedCharacters = CharacterSet.capitalizedLetters.inverted

Buscar siguiente etiqueta y administrar teclado

El campo de texto llama a diferentes métodos de delegado (solo si se establecen delegados) Uno de los métodos de delegado llamado por campo de texto es * - (BOOL) textFieldShouldReturn: (UITextField ) textField

Este método se llama siempre que los usuarios tocan el botón de retorno. Al usar este método, podemos implementar cualquier comportamiento personalizado.

Por ejemplo,

En el siguiente ejemplo, el siguiente respondedor se informará sobre la base de la etiqueta y administrar el teclado. Aquí 20 es la constante, Como la etiqueta asignada al campo de texto es así 50,70,90, etc.

Aquí, al encontrar un nuevo objeto de campo de texto como respondedor, creará el campo de texto actual como nuevo respondedor y abrirá el teclado en consecuencia.

 - (BOOL)textFieldShouldReturn:(UITextField *)textField {

                NSInteger nextTag = textField.tag+20;
                // Try to find next responder
                UIResponder *nextResponder = [textField.superview viewWithTag:nextTag];
                if (nextResponder)
                {
                    // Found next responder, so set it.
                    [nextResponder becomeFirstResponder];
                }
                else
                {
                    // Not found, so remove keyboard.
                    [textField resignFirstResponder];
                }
                return YES;
            }

Acciones cuando un usuario ha comenzado / terminado interactuando con un campo de texto

Para Swift 3.1:

En el primer ejemplo, uno puede ver cómo interceptaría al usuario que interactúa con un campo de texto mientras escribe. De manera similar, hay métodos en el UITextFieldDelegate que se llaman cuando un usuario ha iniciado y finalizado su interacción con un TextField.

Para poder acceder a estos métodos, debe cumplir con el protocolo UITextFieldDelegate y, para cada campo de texto sobre el que desee recibir notificaciones, asigne la clase principal como delegado:

class SomeClass: UITextFieldDelegate {
    
    @IBOutlet var textField: UITextField!

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

}

Ahora podrás implementar todos los métodos de UITextFieldDelegate.

Para recibir una notificación cuando un usuario haya comenzado a editar un campo de texto, puede implementar el método textFieldDidBeginEditing (_ :) así:

func textFieldDidBeginEditing(_ textField: UITextField) {
    // now you can perform some action 
    // if you have multiple textfields in a class, 
    // you can compare them here to handle each one separately
    if textField == emailTextField {
        // e.g. validate email 
    } 
    else if textField == passwordTextField {
        // e.g. validate password 
    } 
}

De manera similar, si se le notifica si un usuario ha finalizado la interacción con un campo de texto, puede usar el método textFieldDidEndEditing (_ :) así:

func textFieldDidEndEditing(_ textField: UITextField) {
    // now you can perform some action 
    // if you have multiple textfields in a class, 
    // you can compare them here to handle each one separately
    if textField == emailTextField {
        // e.g. validate email 
    } 
    else if textField == passwordTextField {
        // e.g. validate password 
    } 
}

Si desea tener control sobre si un TextField debe comenzar / finalizar la edición, los métodos textFieldShouldBeginEditing (_ :) y textFieldShouldEndEditing (_ :) se pueden usar devolviendo verdadero / falso según su lógica necesaria.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow