I have added a textfield in AlertViewController. I don't type anything in the textfield and enter the OK button meaning dismiss the alert view. How should I check the alert textfield length is zero so that alert button actions are disabled. Please help me...
Asked
Active
Viewed 1,857 times
1
-
initially you can disable the button and Using UITextFieldDelegate method public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {} you can disable/enable the button – Sahil Aug 10 '16 at 11:59
-
Possible duplicate of [Prevent dismissal of UIAlertController](http://stackoverflow.com/questions/25628000/prevent-dismissal-of-uialertcontroller) – Mr. Xcoder Aug 10 '16 at 12:19
-
How can you have objective-c and swift tagged? Which one are you using for this? – AMAN77 Aug 10 '16 at 12:30
-
Also check out Guy Kahlons answer here http://stackoverflow.com/questions/24093612/how-to-add-a-textfield-to-uialertview-in-swift ... it might help – AMAN77 Aug 10 '16 at 12:34
1 Answers
5
Try this code.
//
// ViewController.m
// AlertControllerDemo
//
// Created by Nilesh on 8/10/16.
// Copyright © 2016 Nilesh. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<UITextFieldDelegate>
@property(nonatomic, strong)UIAlertAction *okAction;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)showAlertButtonAction:(id)sender {
self.okAction = [UIAlertAction actionWithTitle:@"Okay"
style:UIAlertActionStyleDefault
handler:nil];
self.okAction.enabled = NO;
UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil
message:@"Please Enter your text"
preferredStyle:UIAlertControllerStyleAlert];
[controller addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.delegate = self;
}];
[controller addAction:self.okAction];
[self presentViewController:controller animated:YES completion:nil];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
[self.okAction setEnabled:(finalString.length >= 1)];
return YES;
}
@end

Nilesh Jha
- 1,626
- 19
- 35