您当前的位置: 首页 > 技术文章 > 移动开发

iOS UIAlertController增加输入框UITextField

作者: 时间:2023-10-20阅读数:人阅读

记录今天遇到的一个小需求,要在弹窗上面增加一个输入框,有两种实现方法。

第一种:创建一个UIView在view上添加UITextfield和按钮

第二种:利用系统的UIAlertController增加UITextfield。

这里简单介绍一下第二种方法,具体代码如下:

@property (nonatomic,strong) UITextField *TextField;

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"添加选项" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    //增加取消按钮
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    //增加确定按钮
    UIAlertAction *alertB = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //获取第1个输入框;
        self.TextField = alertController.textFields.firstObject;
        //限制输入框字数
        [self.TextField addTarget:self action:@selector(alertTextAction:) forControlEvents:UIControlEventEditingChanged];
        NSString *moneyStr = [NSString stringWithFormat:@"%@",self.TextField.text];
        
    }];

    //定义第一个输入框;
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入选项内容";
        textField.keyboardType = UIKeyboardTypeDefault;
    }];

    // 修改字体的颜色
    [alertA setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKey:@"_titleTextColor"];
    [alertB setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
    [alertController addAction:alertA];
    [alertController addAction:alertB];
    
    [self presentViewController:alertController animated:true completion:nil];


- (void)alertTextAction:(UITextField *)textField{
    if (textField == self.TextField) {
        if (textField.text.length > 12) {
            textField.text = [textField.text substringToIndex:12];
        }
    }
}

如上记录。。。

本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:licqi@yunshuaiweb.com

加载中~
如果您对我们的成果表示认同并且觉得对你有所帮助可以给我们捐赠。您的帮助是对我们最大的支持和动力!
捐赠我们
扫码支持 扫码支持
扫码捐赠,你说多少就多少
2
5
10
20
50
自定义
您当前余额:元
支付宝
微信
余额

打开支付宝扫一扫,即可进行扫码捐赠哦

打开微信扫一扫,即可进行扫码捐赠哦

打开QQ钱包扫一扫,即可进行扫码捐赠哦