2015-08-30 13 views
7

Ich verwende eine UIAlertController, um einen Dialog mit einer UITextField und einer UIAlertAction Schaltfläche mit der Aufschrift "Ok" zu präsentieren. Wie deaktiviere ich die Taste, bis eine Anzahl von Zeichen (zB 5 Zeichen) in die UITextField eingegeben wird?Enable UIAlertAction von UIAlertController nur nach Eingabe

+0

Sie müssen überprüfen, UITextField Länge .. wenn UITextField Länge 5 ist, dann Schaltfläche aktiviert andere weise nicht –

Antwort

15

Add folgende Eigenschaft in Ihrem Header-Datei

@property(nonatomic, strong)UIAlertAction *okAction; 

dann kopieren Sie den folgenden Code in Ihr viewDidLoad Methode Ihrer ViewController

self.okAction = [UIAlertAction actionWithTitle:@"OK" 
             style:UIAlertActionStyleDefault 
             handler:nil]; 
self.okAction.enabled = NO; 

UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil 
                    message:@"Enter your text" 
                  preferredStyle:UIAlertControllerStyleAlert]; 

[controller addTextFieldWithConfigurationHandler:^(UITextField *textField) { 

    textField.delegate = self; 
}]; 

[controller addAction:self.okAction]; 
[self presentViewController:controller animated:YES completion:nil]; 

auch implementieren die folgenden UITextField Delegatmethode in Ihrer Klasse

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 

    NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
    [self.okAction setEnabled:(finalString.length >= 5)]; 
    return YES; 
} 

Dies sollte

13

arbeiten Sie können einen Beobachter zu Ihrem UITextField hinzufügen:

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) { 
    [textField addTarget:self action:@selector(alertControllerTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; 
} 

aber zuerst deaktivieren Sie Ihre Taste:

okAction.enabled = NO; 

Dann bestätigen Sie in der Methode, die Sie angegeben:

- (void)alertTextFieldDidChange:(UITextField *)sender { 
    UIAlertController *alertController = (UIAlertController *)self.presentedViewController; 
    if (alertController) { 
    UITextField *someTextField = alertController.textFields.firstObject; 
    UIAlertAction *okAction = alertController.actions.lastObject; 
    okAction.enabled = someTextField.text.length > 2; 
    } 
} 
+3

das ist gut, keine Notwendigkeit für zusätzliche Eigenschaften. –

+1

perfekte Verwendung der vorhandenen APIs Dank – malhal

0

Ein besserer Ansatz wäre es, den Benutzer darüber zu warnen, was falsch ist h seine Eingabe nach der Validierung seiner Eingabe, so dass der Benutzer weiß, was die App von ihm erwartet.

- (void)askReasonWithPreviousReason:(NSString *)text 
{ 
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Enter reason" preferredStyle:UIAlertControllerStyleAlert]; 

    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) 
    { 
     textField.text = text; 
    }]; 

    [alertController addAction:[UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) 
           { 
            if ([self isReasonValid:alertController.textFields.firstObject.text]) 
            { 
             UIAlertController *alertController2 = [UIAlertController alertControllerWithTitle:AlertTitle message:@"Are you sure you would like to save?" preferredStyle:UIAlertControllerStyleAlert]; 

             [alertController2 addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) 
                    { 
                     [self saveReason:alertController.textFields.firstObject.text]; 
                    }]]; 
             [alertController2 addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:Nil]]; 

             [self presentViewController:alertController2 animated:YES completion:nil]; 
            } 
           }]]; 

    [alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:Nil]]; 

    [self presentViewController:alertController animated:YES completion:nil]; 
} 

- (BOOL)isReasonValid:(NSString *)reason 
{ 
    NSString *errorMessage = [[NSString alloc] init]; 

    if (reason.length < 5) 
    { 
     errorMessage = @"Reason must be more than 5 characters"; 
    } 
    else if (reason.length > 100) 
    { 
     errorMessage = @"Reason must be less than 100 characters"; 
    } 

    if (errorMessage.length != 0) 
    { 
     UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:errorMessage preferredStyle:UIAlertControllerStyleAlert]; 

     [alertController addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) 
            { 
             [self askReasonWithPreviousReason:reason]; 
            }]]; 

     [self presentViewController:alertController animated:YES completion:nil]; 

     return NO; 
    } 

    return YES; 
} 
4

Swift 3-Implementierung basiert auf soulshined ‚s Antwort:

var someAlert: UIAlertController { 
    let alert = UIAlertController(title: "Some Alert", message: nil, preferredStyle: .alert) 

    alert.addTextField { 
     $0.placeholder = "Write something" 
     $0.addTarget(self, action: #selector(self.textFieldTextDidChange(_:)), for: .editingChanged) 
    } 

    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) 

    let submitAction = UIAlertAction(title: "Submit", style: .default) { _ in 
     // Do something... 
    } 

    submitAction.isEnabled = false 
    alert.addAction(submitAction) 
    return alert 
} 

func textFieldTextDidChange(_ textField: UITextField) { 
    if let alert = presentedViewController as? UIAlertController, 
     let action = alert.actions.last, 
     let text = textField.text { 
     action.isEnabled = text.characters.count > 0 
    } 
} 
+0

sollten Sie 'textField.delegate = self' innerhalb' .addTextField (configurationHandler' – bibscy

0

ich an answer fragen für eine andere Stelle im Grunde hatte die gleiche Frage auf Stackoverflow. Zusammenfassend gibt es mehrere Möglichkeiten, dies zu tun: Verwenden Sie UITextFieldDelegate, Notification, KVO, oder fügen Sie Ereignisbehandlungsziel auf dem Steuerelement einfach hinzu. Meine Lösung ist a simple UIAlertController subclass um das Event-Handling Ziel eingewickelt, die man einfach

alert.addTextField(configurationHandler: { (textField) in 
     textField.placeholder = "Your name" 
     textField.autocapitalizationType = .words 
    }) { (textField) in 
     saveAction.isEnabled = (textField.text?.characters.count ?? 0) > 0 
    } 
durch den Aufruf

bequem sein, wenn Sie mit solchen Warnungen konfigurieren kann mehr als ein paar Mal im Projekt zu tun haben Dies sollte.

Verwandte Themen