如何限制文本输入和计数字符?

时间:2011-04-03 10:54:45

标签: objective-c xcode ios4

我有一个文本字段,我想限制可以输入160个字符的文本。此外,我需要一个计数器来获取当前文本长度。

我使用 NSTimer

解决了这个问题
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self 
         selector:@selector(countText) 
         userInfo:nil 
         repeats:YES];

我用这种方式显示长度:

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

这不是最好的计数器解决方案,因为它取决于时间而不取决于keyUp事件。有没有办法捕获这样的事件并触发方法?

另一方面,是否可以阻止/限制文本输入,例如通过在文本字段中提供最大长度参数?

4 个答案:

答案 0 :(得分:10)

这是(或应该是)委托方法的正确版本:

- (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;
}

答案 1 :(得分:3)

实施一些UITextFieldDelegate协议方法

_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];

返回YES;}     }

答案 2 :(得分:1)

您可以使用委托方法

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

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

}

并设置最大长度并返回NO。

答案 3 :(得分:1)

使用以下代码限制UITextField中的字符,以下代码在UITextField中接受25个字符。

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