对于带输入框的弹出框(UIAlertView),在IOS5.0及以上版本,有一种较为简单的实现方式,即设置UIAlertView的alertViewStyle属性即可。
可供设置的属性如下:
typedefNS_ENUM(NSInteger, UIAlertViewStyle) {UIAlertViewStyleDefault=0, UIAlertViewStyleSecureTextInput, UIAlertViewStylePlainTextInput, UIAlertViewStyleLoginAndPasswordInput};
UIAlertViewStyleDefault,为默认值,不带输入框
UIAlertViewStyleSecureTextInput为密码型输入框,输入的字符显示为圆点儿
UIAlertViewStylePlainTextInput为明文输入框,显示输入的实际字符
UIAlertViewStyleLoginAndPasswordInput为用户名,密码两个输入框,一个明文,一个密码。
取得输入框指针的方法如下:
对于UIAlertViewStyleSecureTextInput和UIAlertViewStylePlainTextInput两种情况,
UITextField *tf = [alert textFieldAtIndex:0]即可取到输入框指针,然后可以进行具体的操作,包括设置键盘样式
对于UIAlertViewStyleLoginAndPasswordInput,除了上面的输入框,依次类推,还可以取到第二个输入框,即:
UITextField *tf2 = [alert textFieldAtIndex:1]
设置键盘样式的方法,即设置UITextField的keyboardType属性。具体值如下:
typedefNS_ENUM(NSInteger, UIKeyboardType){ UIKeyboardTypeDefault,// Default type for the current input method.UIKeyboardTypeASCIICapable,// Displays a keyboard which can enter ASCII characters, non-ASCII keyboards remain activeUIKeyboardTypeNumbersAndPunctuation,// 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).#if__IPHONE_4_1 <= __IPHONE_OS_VERSION_MAX_ALLOWEDUIKeyboardTypeDecimalPad,// A number pad with a decimal point.#endif#if__IPHONE_5_0 <= __IPHONE_OS_VERSION_MAX_ALLOWEDUIKeyboardTypeTwitter,// A type optimized for twitter text entry (easy access to @ #)#endifUIKeyboardTypeAlphabet = UIKeyboardTypeASCIICapable,// Deprecated};
示例代码:
- (IBAction)pressed:(id)sender { UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"message"message:@"please input"delegate:nilcancelButtonTitle:@"cancel"otherButtonTitles:@"OK",nil];// 基本输入框,显示实际输入的内容alert.alertViewStyle= UIAlertViewStylePlainTextInput;// 用户名,密码登录框// alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;// 密码形式的输入框,输入字符会显示为圆点// alert.alertViewStyle = UIAlertViewStyleSecureTextInput;//设置输入框的键盘类型UITextField *tf = [alert textFieldAtIndex:0]; tf.keyboardType= UIKeyboardTypeNumberPad; UITextField *tf2 =nil;if(alert.alertViewStyle== UIAlertViewStyleLoginAndPasswordInput) {// 对于用户名密码类型的弹出框,还可以取另一个输入框tf2 = [alert textFieldAtIndex:1]; tf2.keyboardType= UIKeyboardTypeASCIICapable; }// 取得输入的值NSString* text = tf.text;NSLog(@"INPUT:%@", text);if(alert.alertViewStyle== UIAlertViewStyleLoginAndPasswordInput) {// 对于两个输入框的NSString* text2 = tf2.text;NSLog(@"INPUT2:%@", text2); } [alert show]; }
原文链接在这里:https://segmentfault.com/a/1190000004515976