Программно изменить тип клавиатуры UITextField - PullRequest
169 голосов
/ 04 сентября 2011

Можно ли программно изменить тип клавиатуры uitextfield, чтобы было возможно что-то подобное:

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

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

Ответы [ 12 ]

362 голосов
/ 04 сентября 2011

Существует свойство keyboardType для 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;

Ваш код должен читать

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

if(user is prompted for alphanumeric input)
    [textField setKeyboardType:UIKeyboardTypeDefault];
73 голосов
/ 22 января 2014

Стоит отметить, что если вы хотите, чтобы сфокусированное в данный момент поле для немедленного обновления типа клавиатуры, есть один дополнительный шаг:

// textField is set to a UIKeyboardType other than UIKeyboardTypeEmailAddress

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

Без вызова reloadInputViews клавиатура не изменится, пока выбранное поле ( первый респондент ) не потеряет и не восстановит фокус.

Полный список значений UIKeyboardType можно найти здесь или:

typedef enum : NSInteger {
    UIKeyboardTypeDefault,
    UIKeyboardTypeASCIICapable,
    UIKeyboardTypeNumbersAndPunctuation,
    UIKeyboardTypeURL,
    UIKeyboardTypeNumberPad,
    UIKeyboardTypePhonePad,
    UIKeyboardTypeNamePhonePad,
    UIKeyboardTypeEmailAddress,
    UIKeyboardTypeDecimalPad,
    UIKeyboardTypeTwitter,
    UIKeyboardTypeWebSearch,
    UIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable
} UIKeyboardType;
23 голосов
/ 04 сентября 2011

Да, вы можете, например:

[textField setKeyboardType:UIKeyboardTypeNumberPad];
9 голосов
/ 02 февраля 2016
    textFieldView.keyboardType = UIKeyboardType.PhonePad

Это для Свифта.Также для того, чтобы это функционировало должным образом, оно должно быть установлено после textFieldView.delegate = self

6 голосов
/ 01 октября 2015
_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;
6 голосов
/ 18 октября 2012

, чтобы текстовое поле могло принимать только буквенно-цифровые символы, установите это свойство

textField.keyboardType = UIKeyboardTypeNamePhonePad;
4 голосов
/ 02 апреля 2018

Swift 4

Если вы пытаетесь изменить тип клавиатуры при выполнении условия, выполните следующие действия. Например: если мы хотим изменить тип клавиатуры с По умолчанию на Цифровая клавиатура , когда счетчик текстового поля равен 4 или 5, сделайте следующее:

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 голосов
/ 04 сентября 2011

Для этого есть свойство, которое называется keyboardType.То, что вы хотите сделать, это заменить там, где у вас есть строки @"Number Pad и @"Default на UIKeyboardTypeNumberPad и UIKeyboardTypeDefault.

Ваш новый код должен выглядеть примерно так:

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

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

Удачи!

1 голос
/ 21 февраля 2017

Это UIKeyboardTypes для 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
}

Это пример использования типа клавиатуры из списка:

textField.keyboardType = .numberPad
1 голос
/ 07 июля 2014

для людей, которые хотят использовать UIDatePicker в качестве ввода:

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]];
}
...