开发者

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 scheduledTimerWithTimeInterva开发者_JAVA百科l: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;
}


implement some of UITextFieldDelegate protocol methods

_textEditor.delegate = self;

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    int len = [textField.text length];
    if( len + string.length > max || ){ return NO;}
    else{countLabel.text = [NSString stringWithFormat:@"%i", len];

return YES;} }


you can use the delegate method

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

if(textField.length < max){
    return NO;
}else return YES;

}

and set the max length and return NO.


Use following code to limit the characters in UITextField, following code accepts 25 characters in UITextField.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜