prevent UIAlertView from dismissing

后端 未结 3 1269
梦如初夏
梦如初夏 2021-01-11 22:37

As a form of validation, is there any way to prevent an alert view from dismissing when pressing an \"OK\" button?

Scenario: I have 2 text fields in the alertview fo

3条回答
  •  旧巷少年郎
    2021-01-11 23:39

    You’re doing it the wrong way, you should enable and disable the submit button according to the input. First you have to get access to the button. This is easy, just create the alert without buttons, create a standalone button and add it to the dialog:

    [alert addButtonWithTitle:@"OK"];
    UIButton *submitButton = [[alert subviews] lastObject];
    [submitButton setEnabled:…];
    

    And then you have to set a delegate for those textfields and enable or disable the button when the fields change:

    - (BOOL) textField: (UITextField*) textField
        shouldChangeCharactersInRange: (NSRange) range
        replacementString: (NSString*) string
    {
        int textLength = [textField.text length];
        int replacementLength = [string length];
        BOOL hasCharacters = (replacementLength > 0) || (textLength > 1);
        [self setButtonsAreEnabled:hasCharacters];
    }
    
    // Disable the ‘Return’ key on keyboard.
    - (BOOL) textFieldShouldReturn: (UITextField*) textField
    {
        return NO;
    }
    

    Of course you should wrap all this into a separate class so that you don’t mess up your calling code.

提交回复
热议问题