美文网首页
使用UIAlertView实现带输入框的alertView及设置

使用UIAlertView实现带输入框的alertView及设置

作者: 伯牙呀 | 来源:发表于2017-06-22 14:38 被阅读1656次

    对于带输入框的弹出框(UIAlertView),在 iOS5.0 及以上版本,有一种较为简单的实现方式,即设置 UIAlertViewalertViewStyle 属性即可。

    1、UIAlertView 可供设置的属性如下:
    typedef NS_ENUM(NSInteger, UIAlertViewStyle) {
        // 默认值,不带输入框
        UIAlertViewStyleDefault = 0,
        // 密码型输入框,输入的字符显示为圆点
        UIAlertViewStyleSecureTextInput,
        // 明文输入框,显示输入的实际字符
        UIAlertViewStylePlainTextInput,
        // 用户名,密码两个输入框,一个明文,一个密码
        UIAlertViewStyleLoginAndPasswordInput
    };
    
    UIAlertViewStyleDefault UIAlertViewStyleSecureTextInput UIAlertViewStylePlainTextInput UIAlertViewStyleLoginAndPasswordInput
    2、取得弹窗UIAlertView上的输入框的方法如下:
    • 对于 UIAlertViewStyleSecureTextInputUIAlertViewStylePlainTextInput 两种情况:
    UITextField *textField = [alert textFieldAtIndex:0];
    

    即可取到输入框指针,然后可以进行具体的操作,包括设置键盘样式。

    • 对于 UIAlertViewStyleLoginAndPasswordInput,除了上面的输入框,依次类推,还可以取到第二个输入框。
    UITextField *textField1 = [alert textFieldAtIndex:0];
    UITextField *textField2 = [alert textFieldAtIndex:1];
    
    3、设置按钮动态可用:

    通过代理方法 alertViewShouldEnableFirstOtherButton 来设置:

    - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView {
        if (textField.text.length > 0 && textField2.text.length > 0) {
            return YES;
        }
        return NO;
    }
    

    效果如下:

    alertView设置按钮动态可用
    4、示例代码:
    • 4.1、设置全局变量
    UITextField *textField;
    UITextField *textField2;
    
    • 4.2、初始化UIAlertView并遵循代理
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Title" message:@"message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
    
    // 默认样式,无输入框
    //  alert.alertViewStyle = UIAlertViewStyleDefault;
    // 基本输入框,显示实际输入的内容
    //  alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    // 密码形式的输入框,输入字符会显示为圆点
    //  alert.alertViewStyle = UIAlertViewStyleSecureTextInput;
    // 用户名,密码登录框
    alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    
    // 设置输入框的键盘类型
    textField = [alert textFieldAtIndex:0];
    textField.placeholder = @"Login";
    textField.keyboardType = UIKeyboardTypeNumberPad;
    
    if (alert.alertViewStyle == UIAlertViewStyleLoginAndPasswordInput) {
      // 对于用户名密码类型的弹出框,还可以取另一个输入框
      textField2 = [alert textFieldAtIndex:1];
      textField2.placeholder = @"Password";
      textField2.keyboardType = UIKeyboardTypeASCIICapable;
    }
    
    [alert show];
    
    • 4.3、设置代理方法
    - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView {
        if (textField.text.length > 0 && textField2.text.length > 0) {
            return YES;
        }
        return NO;
    }
    

    使用UIAlertView实现带输入框的alertView及设置键盘样式,按钮动态可用

    使用UIAlertController实现带输入框的alertView和按钮动态可用

    相关文章

      网友评论

          本文标题:使用UIAlertView实现带输入框的alertView及设置

          本文链接:https://www.haomeiwen.com/subject/nmkfcxtx.html