When you want to implement some rules for entering text in UIAlertView
, you should disable the OK
button of your alert view until user follows the rules. You can achieve this with UIAlertViewDelegate
methods. Look into alertViewShouldEnableFirstOtherButton:
.
Return NO
from the method until rule is followed
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
// When return NO, OK button is disabled.
// When return YES, rule is followed and OK button gets enabled.
return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
}
EDIT
The code that I provided was assuming you are using default alert view style textfield, hence the crash.
You should not addSubview
to UIAlertView
, because the view hierarchy of alert view is private. Most recent iOS7 will not display any subviews that user adds on UIAlertView
.So I recommend you do not do this.
From Apple docs,
The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.
Instead, use UIAlertViewStyle
.
Following are the styles supported,
typedef enum {
UIAlertViewStyleDefault = 0,
UIAlertViewStyleSecureTextInput,
UIAlertViewStylePlainTextInput,
UIAlertViewStyleLoginAndPasswordInput
} UIAlertViewStyle;
Use the one that suits your requirement. To validate the input entered by the user use the above method that I suggested. Refer this simple guide/tutorial for using the alert view with these styles.
Hope that helps!