Question

How would I limit the amount of text, that can be entered in a text field in a UIAlertView with my existing code?

I am new to iOS app development.

My code is as following:

if(indexPath.row== 1){
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:@"Enter Novena Day"
                              message:@"Please enter the day of Novena:"
                              delegate:self
                              cancelButtonTitle:@"Cancel"
                              otherButtonTitles:@"Ok", nil];
    [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *textField = [alertView textFieldAtIndex:0];
    textField.keyboardType = UIKeyboardTypeNumberPad;

    [alertView show];

}
Était-ce utile?

La solution

When you initialize the alert view:

[[alertView textFieldAtIndex:0] setDelegate:self];

Now, self here is your view controller. So you need to add <UITextFieldDelegate> to its declaration.

Now implement the delegate method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSUInteger newLength = [textField.text length] + [string length] - range.length;
    return (newLength > self.maxAlertTextFieldLength) ? NO : YES;
}

This is taken from this answer, linked answer in the comments.

Autres conseils

i would suggest to better use a notification

check this

UITextField *textField = [alertView textFieldAtIndex:0];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldMaxLimit:) name:UITextFieldTextDidChangeNotification object:textField];


-(void)textFieldMaxLimit:(NSNotification*)notification
{
  UITextField *textField=(UITextField*)notification.object;

        if ([[textField text] length]>22) //choose your limit for characters
        {
            NSString *lastString=[[textField text] substringToIndex:[[textField text] length] - 1];;
            [textField setText:lastString];
        }
 } 

Implement shouldChangeCharactersInRange delegate , check your condition and return the desired value.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

  BOOL isValid = YES;

  @try
  {
     if(5 < [textField.text length])
     {
        isValid = NO;
     }
  }
  @catch (NSException *exception)
  {
     NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
  }
  @finally
  {
     return isValid;
  }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top