以编程方式更改UITextField键盘类型

182

有没有可能以编程的方式更改uitextfield的键盘类型,以便可以实现类似于这样的功能:

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

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

3
我建议你将“doozy”一词更改为更普遍易懂的术语。请记住,Stack Overflow 是一个国际性网站,而不仅仅是北美地区的一个网站。 - abbood
可能是在iOS上以编程方式更改键盘类型无效的重复问题。 - Parth Patel
12个回答

380

对于 UITextField,有一个 keyboardType 属性:

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

7
请注意,这并不能阻止聪明/疯狂的用户输入其他字符。例如:如果表情符号键盘在他们点击您的数字字段之前就激活了,他们可以自由地在其中输入笑脸。您无法对此做任何事情,这绝对是苹果的错误,但是您应该确保您的代码在数字字段中收到非数字时不会崩溃。 - Steven Fisher
今天发现,这是 UITextInputTraits 协议的一个属性,而 UITextField 采用了该协议。 - rounak
1
在加载到Webview中的HTML输入字段中,是否可以以编程方式更改键盘类型为UIKeyboardTypeNumbersAndPunctuation? - Srini
我在一个项目中以相应的键盘类型编程方式创建了uitextfield。这在几天前还可以工作,但现在不起作用了。没有得到实际原因。 - Protocol

85

值得注意的是,如果您想让一个当前已聚焦的输入框立即更新键盘类型,需要额外执行一步操作:

// 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;

这是有用的信息-我建议进行问答式自我回答问题,以提取有关当前聚焦字段输入更改的信息(当我找到此答案时,这就是我正在寻找的)。 - Stonz2
1
值得一提的是,在当前未聚焦的文本框上调用reloadInputViews不会立即更改键盘类型。因此最好先调用[textfield becomeFirstResponder],然后再调用[textField reloadInputViews]。 - Qiulang
1
我漏掉了[textField reloadInputViews];。谢谢! - Islam
1
调用 reloadInputViews 对于定制的 UITextInput 实现也适用。 - Paul Gardiner

23

是的,你可以这样做:

[textField setKeyboardType:UIKeyboardTypeNumberPad];

12
    textFieldView.keyboardType = UIKeyboardType.PhonePad

这是针对Swift的。为了使它正常工作,它必须在textFieldView.delegate = self之后进行设置。


9

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()
 }

9

若要使文本框仅接受字母和数字,请设置此属性。

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;

2

这个属性被称为 keyboardType

你需要做的是将字符串 @"Number Pad"@"Default" 替换为 UIKeyboardTypeNumberPadUIKeyboardTypeDefault

你的新代码应该类似于:

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

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

Good Luck!


1

对于想要使用 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]];
}

1

这是Swift 3中的UIKeyboardTypes

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接