Modifica programmatica del tipo di tastiera UITextField


175

È possibile modificare a livello di programmazione il tipo di tastiera di un campo uitext in modo che sia possibile qualcosa del genere:

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

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

3
ti suggerirei di cambiare il termine doozyin qualcosa che è più comunemente comprensibile .. tieni presente che SO è un sito internazionale e non uno nordamericano
— circa il

Risposte:


371

C'è una keyboardTypeproprietà per un 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;

Il tuo codice dovrebbe essere letto

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

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

7
Nota che ciò non impedisce a un utente intelligente / squilibrato di inserire altri caratteri. Ad esempio: se la tastiera Emoji era attiva prima che toccassero il campo del numero, sono liberi di digitare le faccine. Non c'è niente che tu possa fare al riguardo, ed è sicuramente un bug di Apple, ma dovresti assicurarti che il tuo codice non si blocchi se ottieni non numeri in un campo numerico.
— Steven Fisher,

Oggi scoperto, questa è una proprietà del UITextInputTraitsprotocollo, che UITextFieldadotta.
— Rounak,

1
È possibile modificare a livello di programmazione il tipo di tastiera come UIKeyboardTypeNumbersAndPunctuation, per i campi di input HTML caricati in Webview?
— Srini,

Ho creato uitextfield a livello di programmazione in un progetto con il rispettivo tipo di tastiera. questo è stato svegliato pochi giorni fa. ma ora questo non funziona. Non si ottiene la vera ragione
— Rahul Phate,

78

Vale la pena notare che se si desidera che un campo attualmente focalizzato aggiorni immediatamente il tipo di tastiera, c'è un ulteriore passaggio:

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

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

Senza la chiamata a reloadInputViews, la tastiera non cambierà finché il campo selezionato (il primo risponditore ) non perde e riacquista lo stato attivo.

Un elenco completo dei UIKeyboardTypevalori è disponibile qui oppure:

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

Queste sono informazioni utili da sapere, suggerirei di fare una domanda con risposta in stile Q & A solo per estrarre le informazioni sulla modifica dell'input di campo attualmente focalizzato (questo è quello che stavo cercando quando ho trovato questa risposta)
— Stonz2

1
Vale anche la pena ricordare che la chiamata a reloadInputViews sul campo di testo attualmente NON focalizzato non cambierà immediatamente il tipo di tastiera. Quindi meglio chiamare [textfield diventatoFirstResponder] prima poi [textField reloadInputViews]
— Qiulang

1
Era [textField reloadInputViews];che mi mancava. Grazie!
— Islam Q.

1
La chiamata reloadInputViewsfunziona anche per UITextInputimplementazioni su misura .
— Paul Gardiner,

23

Sì, ad esempio:

[textField setKeyboardType:UIKeyboardTypeNumberPad];

9
    textFieldView.keyboardType = UIKeyboardType.PhonePad

Questo è per rapido. Inoltre, affinché funzioni correttamente, deve essere impostato dopotextFieldView.delegate = self


7

per fare in modo che il campo di testo accetti i caratteri alfanumerici impostare solo questa proprietà

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

Se stai cercando di cambiare il tipo di tastiera quando viene soddisfatta una condizione, segui questa procedura. Ad esempio: se vogliamo cambiare il tipo di tastiera da Predefinito a Tastierino numerico quando il conteggio del campo di testo è 4 o 5, procedere come segue:

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

C'è una proprietà per questo chiamato keyboardType. Quello che vorrai fare è sostituire dove hai le stringhe @"Number Pade @"Defaultcon UIKeyboardTypeNumberPadeUIKeyboardTypeDefault .

Il tuo nuovo codice dovrebbe assomigliare a questo:

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

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

In bocca al lupo!


1

per le persone che vogliono utilizzare UIDatePickercome input:

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

Questo è UIKeyboardTypesper 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
}

Questo è un esempio per usare un tipo di tastiera dall'elenco:

textField.keyboardType = .numberPad

0

Cambia a livello di tastiera UITextField tipo di tastiera rapido 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

Ecco il tipo di tastiera in 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
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.