在UIAlertView中更改UITextField的键盘类型

isa*_*ced 4 objective-c uialertview ios

我创建了一个UIAlertView,其alertViewStyle设置为UIAlertViewStylePlainTextInput.

我想更改键盘类型,但不是通过添加子视图.

我的代码:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"a" message:@"b" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:@"aaa", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;  
[alert show];
Run Code Online (Sandbox Code Playgroud)

nsg*_*ver 42

如果您想要呈现输入样式,首先在您的类中实现UIAlertViewDelegate.

其次,当您呈现alertView时,将委托设置为self.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"a" message:@"b" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"aaa", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;  
[alert show];'
Run Code Online (Sandbox Code Playgroud)

如果要更改特定字段的键盘类型,请执行此操作

例如,对于第一场,它将使键盘数字化.

[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[[alert textFieldAtIndex:0] becomeFirstResponder];
Run Code Online (Sandbox Code Playgroud)

更新iOS 8.0 Swift

从ios 8.0开始 UIAlertView,不推荐使用,因此您可能需要使用UIAlertController

 var alert = UIAlertController(title: "Title", message: "Your msg", 
                preferredStyle: UIAlertControllerStyle.Alert)

        alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, 
              handler:yourHandler))

        alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
            textField.placeholder = "Password"
            textField.secureTextEntry = true  // setting the secured text for using password
            textField.keyboardType = UIKeyboardType.Default
        })
Run Code Online (Sandbox Code Playgroud)