iOS UIAlertController实现带输入框的样式

释放双眼,带上耳机,听听看~!
UIAlertController设置按钮动态可用

// 定义全局变量
UITextField *textField1;
UITextField *textField2;
UIAlertAction *cancelAction;
UIAlertAction *okAction;
- (void)showAlertController {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];
cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了Cancel");
}];
okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"点击了OK");
}];
[alertController addAction:okAction];
[alertController addAction:cancelAction];
// 添加文本框(只能添加到UIAlertControllerStyleAlert的样式,如果是preferredStyle:UIAlertControllerStyleActionSheet则会崩溃)
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.placeholder = @"Login";
// 监听文字改变的方法,也可以通过通知
[textField addTarget:self action:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
textField1 = textField;
}];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.secureTextEntry = YES;  // 密文形式显示
textField.placeholder = @"Password";
// 监听文字改变的方法
[textField addTarget:self action:@selector(textFieldDidChange:)forControlEvents:UIControlEventEditingChanged];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
textField2 = textField;
}];
if (textField1.text.length > 0 && textField2.text.length > 0) {
okAction.enabled = YES;
} else {
okAction.enabled = NO;
}
[self presentViewController:alertController animated:YES completion:nil];
}
// 监听文字改变的方法
- (void)textFieldDidChange:(UITextField *)textField {
if (textField1.text.length > 0 && textField2.text.length > 0) {
okAction.enabled = YES;
} else {
okAction.enabled = NO;
}
}
// 通过通知来监听文字改变
- (void)textFieldDidChangeNotification:(NSNotification *)notification {
UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
if (alertController) {
//        UITextField *login = alertController.textFields.firstObject;
//        UITextField *passw = alertController.textFields.lastObject;
//        UIAlertAction *cancelAction = alertController.actions.firstObject;
//        UIAlertAction *okAction = alertController.actions.lastObject;
if (textField1.text.length > 0 && textField2.text.length > 0) {
okAction.enabled = YES;
} else {
okAction.enabled = NO;
}
}
}

 

人已赞赏
iOS文章

iOS 给安装包瘦身

2020-1-1 16:20:47

iOS文章

iOS中UITabBarControlle的使用详细教程

2020-1-1 17:04:09

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索