0

I'm creating a text input uialertview using the method below.

[dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];

How can I limit the number of characters the user is able to input?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
user1542125
  • 593
  • 6
  • 16

2 Answers2

3

Try this code

First add UITextFieldDelegate

UIAlertView *dialog = [[UIAlertView alloc]init];// Setup your alert 
[dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
[dialog textFieldAtIndex:0].placeholder = @"";//add this if you need
[dialog textFieldAtIndex:0].delegate = self;

and add textfield delegate as per Check this Answer

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

Maybe it will help you.

Community
  • 1
  • 1
ChintaN -Maddy- Ramani
  • 5,156
  • 1
  • 27
  • 48
0

If you have instance of your alertView just do the following

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([self.alertView textFieldAtIndex:0])
    {
      NSUInteger newLength = [textField.text length] + [string length] - range.length;
      return (newLength > 25) ? NO : YES;
    }
    return YES; // suppress warning about control reaching end of non-void function
}
Zev Eisenberg
  • 8,080
  • 5
  • 38
  • 82
Pancho
  • 4,099
  • 1
  • 21
  • 32