prevent UIAlertView from dismissing

吃可爱长大的小学妹 提交于 2019-12-04 00:41:33

问题


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 for username/password. If both are empty and the user presses "OK", I do not want the alert to be dismissed.


回答1:


iOS 5 introduces a new property to UIAlertView to handle exactly this problem.

alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;

Apple documentation on UIAlertView.

Add the new UIAlertViewDelegate method to handle the enabling/disabling of the button.

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView

Apple documentation on UIAlertViewDelegate.




回答2:


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.




回答3:


I don't believe you actually need to pass in any button names. Just take out your OK button string and leave it as "nil".



来源:https://stackoverflow.com/questions/1947783/prevent-uialertview-from-dismissing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!