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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With