iOS5中提供了几种便利的UIAlertView,如下所示:
- (IBAction)showDefaultAlertView:(id)sender { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"DefaultStyle" message:@"the default alert view style" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; [alertView show]; [alertView release]; } - (IBAction)showSecureTextAlertView:(id)sender { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"SecureTextStyle" message:@"Enter secure text" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; alertView.alertViewStyle = UIAlertViewStyleSecureTextInput; [alertView show]; [alertView release]; } - (IBAction)showPlainTextAlertView:(id)sender { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"PlainTextStyle" message:@"Enter plain text" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; alertView.alertViewStyle = UIAlertViewStylePlainTextInput; [alertView show]; [alertView release]; } - (IBAction)showLoginPassAlertView:(id)sender { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"LoginAndPaswordStyle" message:@"Enter login and password" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput; [alertView show]; [alertView release]; }
下面是对应的代理方法:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { switch (alertView.alertViewStyle) { case UIAlertViewStylePlainTextInput: { UITextField *textField = [alertView textFieldAtIndex:0]; NSLog(@"Plain text input: %@", textField.text); } break; case UIAlertViewStyleSecureTextInput: { UITextField *textField = [alertView textFieldAtIndex:0]; NSLog(@"Secure text input: %@", textField.text); } break; case UIAlertViewStyleLoginAndPasswordInput: { UITextField *loginField = [alertView textFieldAtIndex:0]; NSLog(@"Login input: %@", loginField.text); UITextField *passwordField = [alertView textFieldAtIndex:1]; NSLog(@"Password input: %@", passwordField.text); } break; default: break; } } - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView { UIAlertViewStyle style = alertView.alertViewStyle; if ((style == UIAlertViewStyleSecureTextInput) || (style == UIAlertViewStylePlainTextInput) || (style == UIAlertViewStyleLoginAndPasswordInput)) { UITextField *textField = [alertView textFieldAtIndex:0]; if ([textField.text length] == 0) { return NO; } } return YES; }