【问题标题】:UITextView: characters count is not right when the backspace is typed inUITextView:输入退格键时字符数不正确
【发布时间】:2012-09-10 14:00:17
【问题描述】:

我想在输入 UITextView 时显示字符数。但是当我按下删除/退格键时我很困惑。

我用:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

我的代码是:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSLog(@"input %d chars",textView.text.length + 1);
    return YES;
}

当我输入 hello 时,它显示“输入 5 个字符”;但是如果我单击删除/退格键,数字变为 6,而不是 4。这是怎么回事?输入时如何知道 UITextView 中的确切字符数?

【问题讨论】:

    标签: objective-c ios uitextviewdelegate


    【解决方案1】:

    您可以在编辑后获取文本字段中的文本,然后检查其长度:

    NSString* newString = [textField1.text stringByReplacingCharactersInRange:range withString:string];
    int newLength = [newString length];
    

    【讨论】:

      【解决方案2】:

      这很明显:)

      你正在输出长度+1

      textView.text.length + 1
      

      但退格键不会使长度 1 变长,而是使其变短 1!

      - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
      
          // Do the replacement
          NSString *newText = [textView.text stringByReplacingCharactersInRange:range withString:text];
      
         // See what comes out
          NSLog(@"input %d chars", newText.length);
      
          return YES;
      }
      

      【讨论】:

      • 非常感谢!我的方法很糟糕。我加 1 是因为我认为 1 是 text.length。现在我从你的回答中知道该怎么做。
      【解决方案3】:

      文本视图发送textView:shouldChangeTextInRange:replacementText:它实际上改变它的文本。

      它发送textViewDidChange:它改变了它的文本。

      所以只需实现textViewDidChange:

      - (void)textViewDidChange:(UITextView *)textView {
          NSLog(@"textView.text.length = %u", textView.text.length);
      }
      

      【讨论】:

        【解决方案4】:

        检查替换文本参数的长度,在退格的情况下为零。

        还有另一种情况需要考虑,用户选择一系列字符并将文本粘贴到字段中。在这种情况下,您还应该减去替换文本的长度。

        NSLog(@"New length is: %d chars",textView.text.length - range.length + text.length);
        

        【讨论】:

        • 如果他们选择 5 个字符并剪切它们会怎样 - 那么 text.length 将为 0 但 textView 文本的新长度应该少 5 个。
        • 好点 - 你也必须考虑范围的长度,我匆忙忘记了。
        • 我会打电话给stringByReplacingCharactersInRange:withString: 让 iOS 为我处理 :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 2013-08-22
        相关资源
        最近更新 更多