Cambiar programáticamente el tipo de teclado UITextField


175

¿Es posible cambiar programáticamente el tipo de teclado de uitextfield para que sea posible algo como esto:

if(user is prompted for numeric input only)
    [textField setKeyboardType: @"Number Pad"];

if(user is prompted for alphanumeric input)
    [textField setKeyboardType: @"Default"];

3
me gustaría sugerir que cambie el término doozya algo que es más comúnmente comprensible .. tener en cuenta para es un sitio internacional y no un norteamericano uno
— Abbood

Respuestas:


371

Hay una keyboardTypepropiedad para UITextField:

typedef enum {
    UIKeyboardTypeDefault,                // Default type for the current input method.
    UIKeyboardTypeASCIICapable,           // Displays a keyboard which can enter ASCII characters, non-ASCII keyboards remain active
    UIKeyboardTypeNumbersAndPunctuation,  // Numbers and assorted punctuation.
    UIKeyboardTypeURL,                    // A type optimized for URL entry (shows . / .com prominently).
    UIKeyboardTypeNumberPad,              // A number pad (0-9). Suitable for PIN entry.
    UIKeyboardTypePhonePad,               // A phone pad (1-9, *, 0, #, with letters under the numbers).
    UIKeyboardTypeNamePhonePad,           // A type optimized for entering a person's name or phone number.
    UIKeyboardTypeEmailAddress,           // A type optimized for multiple email address entry (shows space @ . prominently).
    UIKeyboardTypeDecimalPad,             // A number pad including a decimal point
    UIKeyboardTypeTwitter,                // Optimized for entering Twitter messages (shows # and @)
    UIKeyboardTypeWebSearch,              // Optimized for URL and search term entry (shows space and .)

    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable, // Deprecated

} UIKeyboardType;

Tu código debería leer

if(user is prompted for numeric input only)
    [textField setKeyboardType:UIKeyboardTypeNumberPad];

if(user is prompted for alphanumeric input)
    [textField setKeyboardType:UIKeyboardTypeDefault];

77
Tenga en cuenta que esto no impide que un usuario inteligente / trastornado ingrese otros caracteres. Por ejemplo: si el teclado Emoji estaba activo antes de tocar su campo de número, pueden escribir caritas sonrientes en él. No hay nada que pueda hacer al respecto, y definitivamente es un error de Apple, pero debe asegurarse de que su código no se bloquee si obtiene números que no son números en un campo numérico.
— Steven Fisher

Descubierto hoy, esta es una propiedad del UITextInputTraitsprotocolo, que UITextFieldadopta.
— rounak

1
¿Es posible cambiar programáticamente el tipo de teclado como UIKeyboardTypeNumbersAndPunctuation, para los campos de entrada HTML cargados en la vista web?
— Srini

Creé uitextfield programáticamente en un proyecto con el tipo de teclado respectivo. Esto se hizo hace unos días. Pero ahora esto no funciona. No entiendo la razón real
— Rahul Phate

78

Vale la pena señalar que si desea que un campo enfocado actualmente actualice el tipo de teclado de inmediato, hay un paso adicional:

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

[textField setKeyboardType:UIKeyboardTypeEmailAddress];
[textField reloadInputViews];

Sin la llamada a reloadInputViews, el teclado no cambiará hasta que el campo seleccionado (el primer respondedor ) pierda y recupere el enfoque.

Puede encontrar una lista completa de los UIKeyboardTypevalores aquí , o:

typedef enum : NSInteger {
    UIKeyboardTypeDefault,
    UIKeyboardTypeASCIICapable,
    UIKeyboardTypeNumbersAndPunctuation,
    UIKeyboardTypeURL,
    UIKeyboardTypeNumberPad,
    UIKeyboardTypePhonePad,
    UIKeyboardTypeNamePhonePad,
    UIKeyboardTypeEmailAddress,
    UIKeyboardTypeDecimalPad,
    UIKeyboardTypeTwitter,
    UIKeyboardTypeWebSearch,
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;

Esta es información útil para saber: sugeriría hacer una pregunta de respuesta automática al estilo de preguntas y respuestas solo para extraer la información sobre el cambio de entrada de campo actualmente enfocado (eso es lo que estaba buscando cuando encontré esta respuesta)
— Stonz2

1
También vale la pena mencionar que llamar a reloadInputViews en el campo de texto que actualmente NO está enfocado no cambiará el tipo de teclado de inmediato. Así que mejor llame primero [textfield BecomeFirstResponder] luego [textField reloadInputViews]
— Qiulang

1
Era [textField reloadInputViews];que me faltaba. ¡Gracias!
— Islam Q.

1
Las llamadas reloadInputViewstambién funcionan para UITextInputimplementaciones a medida .
— Paul Gardiner

23

Sí, puedes, por ejemplo:

[textField setKeyboardType:UIKeyboardTypeNumberPad];

9
    textFieldView.keyboardType = UIKeyboardType.PhonePad

Esto es para rápido. Además, para que esto funcione correctamente, debe configurarse después detextFieldView.delegate = self


7

para hacer que el campo de texto acepte alfanumérico solo establezca esta propiedad

textField.keyboardType = UIKeyboardTypeNamePhonePad;

6
_textField .keyboardType = UIKeyboardTypeAlphabet;
_textField .keyboardType = UIKeyboardTypeASCIICapable;
_textField .keyboardType = UIKeyboardTypeDecimalPad;
_textField .keyboardType = UIKeyboardTypeDefault;
_textField .keyboardType = UIKeyboardTypeEmailAddress;
_textField .keyboardType = UIKeyboardTypeNamePhonePad;
_textField .keyboardType = UIKeyboardTypeNumberPad;
_textField .keyboardType = UIKeyboardTypeNumbersAndPunctuation;
_textField .keyboardType = UIKeyboardTypePhonePad;
_textField .keyboardType = UIKeyboardTypeTwitter;
_textField .keyboardType = UIKeyboardTypeURL;
_textField .keyboardType = UIKeyboardTypeWebSearch;

5

Swift 4

Si está intentando cambiar su tipo de teclado cuando se cumple una condición, siga esto. Por ejemplo: si queremos cambiar el tipo de teclado de Predeterminado a Teclado numérico cuando el recuento del campo de texto es 4 o 5, haga esto:

textField.addTarget(self, action: #selector(handleTextChange), for: .editingChanged)

@objc func handleTextChange(_ textChange: UITextField) {
 if textField.text?.count == 4 || textField.text?.count == 5 {
   textField.keyboardType = .numberPad
   textField.reloadInputViews() // need to reload the input view for this to work
 } else {
   textField.keyboardType = .default
   textField.reloadInputViews()
 }

2

Hay una propiedad para esto llamada keyboardType. Lo que querrás hacer es reemplazar donde tienes cadenas @"Number Pady @"Defaultcon UIKeyboardTypeNumberPady UIKeyboardTypeDefault.

Su nuevo código debería verse así:

if(user is prompted for numeric input only)
    [textField setKeyboardType:UIKeyboardTypeNumberPad];

else if(user is prompted for alphanumeric input)
    [textField setKeyboardType:UIKeyboardTypeDefault];

¡Buena suerte!


1

para las personas que desean usar UIDatePickercomo entrada:

UIDatePicker *timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 0, 0)];
[timePicker addTarget:self action:@selector(pickerChanged:)
     forControlEvents:UIControlEventValueChanged];
[_textField setInputView:timePicker];

// pickerChanged:
- (void)pickerChanged:(id)sender {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"d/M/Y"];
    _textField.text = [formatter stringFromDate:[sender date]];
}

1

Este es el UIKeyboardTypespara Swift 3:

public enum UIKeyboardType : Int {

    case `default` // Default type for the current input method.
    case asciiCapable // Displays a keyboard which can enter ASCII characters
    case numbersAndPunctuation // Numbers and assorted punctuation.
    case URL // A type optimized for URL entry (shows . / .com prominently).
    case numberPad // A number pad with locale-appropriate digits (0-9, ۰-۹, ०-९, etc.). Suitable for PIN entry.
    case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).
    case namePhonePad // A type optimized for entering a person's name or phone number.
    case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).

    @available(iOS 4.1, *)
    case decimalPad // A number pad with a decimal point.

    @available(iOS 5.0, *)
    case twitter // A type optimized for twitter text entry (easy access to @ #)

    @available(iOS 7.0, *)
    case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).

    @available(iOS 10.0, *)
    case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.


    public static var alphabet: UIKeyboardType { get } // Deprecated
}

Este es un ejemplo para usar un tipo de teclado de la lista:

textField.keyboardType = .numberPad

0

Cambie programáticamente el tipo de teclado UITextField swift 3.0

lazy var textFieldTF: UITextField = {

    let textField = UITextField()
    textField.placeholder = "Name"
    textField.frame = CGRect(x:38, y: 100, width: 244, height: 30)
    textField.textAlignment = .center
    textField.borderStyle = UITextBorderStyle.roundedRect
    textField.keyboardType = UIKeyboardType.default //keyboard type
    textField.delegate = self
    return textField 
}() 
override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(textFieldTF)
}

0

Estos son los tipos de teclado en Swift 4.2

// UIKeyboardType
//
// Requests that a particular keyboard type be displayed when a text widget
// becomes first responder. 
// Note: Some keyboard/input methods types may not support every variant. 
// In such cases, the input method will make a best effort to find a close 
// match to the requested type (e.g. displaying UIKeyboardTypeNumbersAndPunctuation 
// type if UIKeyboardTypeNumberPad is not supported).
//
public enum UIKeyboardType : Int {


    case `default` // Default type for the current input method.

    case asciiCapable // Displays a keyboard which can enter ASCII characters

    case numbersAndPunctuation // Numbers and assorted punctuation.

    case URL // A type optimized for URL entry (shows . / .com prominently).

    case numberPad // A number pad with locale-appropriate digits (0-9, ۰-۹, ०-९, etc.). Suitable for PIN entry.

    case phonePad // A phone pad (1-9, *, 0, #, with letters under the numbers).

    case namePhonePad // A type optimized for entering a person's name or phone number.

    case emailAddress // A type optimized for multiple email address entry (shows space @ . prominently).

    @available(iOS 4.1, *)
    case decimalPad // A number pad with a decimal point.

    @available(iOS 5.0, *)
    case twitter // A type optimized for twitter text entry (easy access to @ #)

    @available(iOS 7.0, *)
    case webSearch // A default keyboard type with URL-oriented addition (shows space . prominently).

    @available(iOS 10.0, *)
    case asciiCapableNumberPad // A number pad (0-9) that will always be ASCII digits.


    public static var alphabet: UIKeyboardType { get } // Deprecated
}
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.