【问题标题】:How to limit text input and count characters?如何限制文本输入和计数字符?
【发布时间】:2011-04-03 10:54:44
【问题描述】:

我有一个文本字段,我想将可输入的文本限制为 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 事件。有没有办法捕获这样的事件并触发方法?

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

【问题讨论】:

    标签: objective-c xcode ios4


    【解决方案1】:

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

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

    【讨论】:

    • 这对于类英语(非转移)语言来说是一个很好的答案,但对于一些需要拼写转移的语言,例如日语或中文,它有时会计算错误。例如,当您在拼写时尝试在日文键盘上按“に”时,它会计为 2,但正常时它会计为 1。此外,当您在拼写时按删除按钮时,计数就搞砸了...
    • 很好的答案...非常感谢
    • @RalphZhouYuan 是正确的。 -[UITextField addTarget:forEvent:] 已经足够好了。
    【解决方案2】:

    实现一些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];
    

    返回是;} }

    【讨论】:

    • 这允许文本中包含 161 个字符。一旦有 161 个,就禁用删除。它允许粘贴超过 160 个字符的文本。问题不是那么小。
    • 是的,第一个问题已经解决。但是你不能在选择的 150 个字符上粘贴 20 个字符 ;-)
    • 我只是想指出方法,而不是 100% 解决问题;)请参阅fluchtpunkt 的回答
    【解决方案3】:

    你可以使用委托方法

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    if(textField.length < max){
        return NO;
    }else return YES;
    

    }

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

    【讨论】:

    • textFieldShouldBeginEditing: 只会阻止开始输入。每次用户输入按键时都必须进行阈值检查。
    【解决方案4】:

    使用以下代码限制 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;
          }
    

    【讨论】:

      猜你喜欢
      • 2017-01-23
      • 2011-07-28
      • 2015-01-31
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 2021-02-24
      • 2012-02-11
      • 1970-01-01
      相关资源
      最近更新 更多