2015-08-30 5 views
7

Używam UIAlertController, aby wyświetlić okno dialogowe z przyciskiem UITextField i jednym UIAlertAction oznaczonym "Ok". Jak wyłączyć przycisk, dopóki liczba znaków (np. 5 znaków) nie zostanie wprowadzona do UITextField?Włącz UIAlertAction z UIAlertController tylko po wprowadzeniu

+0

musisz sprawdzić długość UITextField .. jeśli UITextField ma długość 5 to przycisk umożliwi inne mądre nie –

Odpowiedz

15

Dodaj następujący nieruchomość w pliku nagłówkowym

@property(nonatomic, strong)UIAlertAction *okAction; 

skopiuj poniższy kod w swoim sposobie swojej 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]; 

Również viewDidLoad wdrożyć następujące metody UITextField delegata w swojej klasie

- (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; 
} 

To powinno działać

13

Możesz dodać obserwatora do UITextField:

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

ale najpierw wyłączyć przycisk:

okAction.enabled = NO; 

Następnie zatwierdź go w sposobie określonym:

- (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

to jest dobre, bez potrzeby dodatkowych właściwości. –

+1

perfekcyjne wykorzystanie istniejących API dzięki – malhal

0

Lepszym rozwiązaniem byłoby poinformowanie użytkownika o tym, co jest złym dowcipem h jego dane wejściowe po sprawdzeniu poprawności danych wejściowych, aby użytkownik wiedział, czego oczekuje od niego aplikacja.

- (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 realizacja na podstawie soulshined „s odpowiedź:

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

powinieneś ustawić 'textField.delegate = self' wewnątrz' .addTextField (configurationHandler' – bibscy

0

miałem an answer na innym stanowisku prośbą zasadzie to samo pytanie na StackOverflow. Podsumowując, można to zrobić na kilka sposobów: użyj UITextFieldDelegate, Notification, KVO lub dodaj cel sterowania zdarzeniami do kontrolki. Moje rozwiązanie jest a simple UIAlertController subclass owinięty wokół tarczy obsługi zdarzeń, które można skonfigurować po prostu dzwoniąc

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

To powinno być wygodne, jeśli masz do czynienia z takimi wpisami więcej niż kilka razy w projekcie.