Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit text input and count characters?

I have a text field and I want to limit the text that can be entered to 160 chars. Besides I need a counter to get the current text length.

I solved it using a NSTimer:

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self 
         selector:@selector(countText) 
         userInfo:nil 
         repeats:YES];

And I display the length this way:

-(void)countText{
    countLabel.text = [NSString stringWithFormat:@"%i",
                                _textEditor.text.length];
}

This is not the best counter solution, because it depends on time and not on keyUp event. Is there a way to catch such an event and triggere a method?

The othere thing is, is it possible to block/limit text input, e.g. by providing a max length parameter on the text field?

like image 281
UpCat Avatar asked Dec 04 '22 22:12

UpCat


1 Answers

This is (or should be) the correct version of the delegate method:

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// "Length of existing text" - "Length of replaced text" + "Length of replacement text"
    NSInteger newTextLength = [aTextView.text length] - range.length + [text length];

    if (newTextLength > 160) {
        // don't allow change
        return NO;
    }
    countLabel.text = [NSString stringWithFormat:@"%i", newTextLength];
    return YES;
}
like image 54
Matthias Bauch Avatar answered Jan 18 '23 19:01

Matthias Bauch