Learner Learner - 3 months ago 10x
iOS Question

Limiting number of characters that an user might input is not working

I have to limit the number of characters that an user might input in a textview. Im limiting it to 500 characters
Following is my code,

- (void)textViewDidChange:(UITextView *)textView{

NSInteger restrictedLength=500;

NSString *temp=textView.text;
NSLog(@"hekk %ld",[[textView text]length]);
if([[textView text] length] > restrictedLength){
textView.text=[temp substringToIndex:[temp length]-1];

The problem is that, if the user edits the textview using keyboard then the user may not be able to type more than 500 characters. But if the user copy paste the texts, the user is able to input more that 500 characters. Hoe can I sort this out?


Try this.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    int maxCharacters = 500;
    NSString *newString = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if(newString.length > maxCharacters){
        textView.text = [newString substringToIndex:maxCharacters];
        return NO;
    return YES;