Sunday, July 8, 2012

UIAlertView Text, Secure Text and Login Password Input

In iOS 5, UIAlertView was updated to include support for text input, secure text input and login/password input. Say goodbye to the creative code (read hacks) many of us have tried, to add similar functionality.
The screenshots below show examples of each new alert style:


To set the desired style, the following property has been added:
@property(nonatomic, assign) UIAlertViewStyle alertViewStyle
Each of the news styles, including a reference to the default (original alert type) are below:
typedef enum {
    UIAlertViewStyleDefault = 0,
    UIAlertViewStyleSecureTextInput,
    UIAlertViewStylePlainTextInput,
    UIAlertViewStyleLoginAndPasswordInput
} UIAlertViewStyle;
Example code to create each style of alert follow:
// Plain text alert
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Feedback" 
                            message:[NSString stringWithFormat:@"Your comments are welcome:"]
                            delegate:self cancelButtonTitle:@"Ok" 
                            otherButtonTitles:nil];
 
  [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
  [alert show];
  [alert release];
 
 
  // Secure text alert
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Secure Information " 
                            message:[NSString stringWithFormat:@"Enter the project code name:"]
                            delegate:self cancelButtonTitle:@"Cancel" 
                            otherButtonTitles:@"Ok", nil];
 
  [alert setAlertViewStyle:UIAlertViewStyleSecureTextInput];
  [alert show];
  [alert release];
 
 
  // Login and password alert
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Login" 
                            message:[NSString stringWithFormat:@"Enter Login ID and Password:"]
                            delegate:self cancelButtonTitle:@"Ok" 
                            otherButtonTitles:nil];
 
  [alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];  
  [alert show];
  [alert release];
To access the text input from any of the above, call the method below::
- (UITextField *)textFieldAtIndex:(NSInteger)textFieldIndex
The index is 0 to access the plain text, secure text and login ID values. To access the password text, the index must be set to 1.
- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
  // If plain text or secure text
  if ([alert alertViewStyle] == UIAlertViewStylePlainTextInput || [alert alertViewStyle] == UIAlertViewStyleSecureTextInput)
    NSLog(@"Text: %@", [[alert textFieldAtIndex:0] text]);
  // Login and password
  else if ([alert alertViewStyle] == UIAlertViewStyleLoginAndPasswordInput)
  {
    NSLog(@"Login: %@", [[alert textFieldAtIndex:0] text]);
    NSLog(@"Password: %@", [[alert textFieldAtIndex:1] text]);  
  }
}

No comments:

Post a Comment

Popular Posts