如何在UITextView中检测用户输入字符

Jas*_*hao 15 iphone objective-c uitextview ios

如何在UITextView中检测用户输入字符?

例如:(在UITextView NOT UITextField中)

当用户输入字母"a"时,触发事件.当用户输入"do it"时,触发另一个事件.或输入"http://www.stackoverflow.com"触发事件.

谢谢

Sel*_*vin 26

您可以监视此委托方法中的TextView内容更改并触发必要的操作.

- (void)textViewDidChange:(UITextView *)textView
{
    //Access the textView Content
    //From here you can get the last text entered by the user
    NSArray *stringsSeparatedBySpace = [textView.text componentsSeparatedByString:@" "];
    //then you can check whether its one of your userstrings and trigger the event
    NSString *lastString = [stringsSeparatedBySpace lastObject];
    if([lastString isEqualToString:@"http://www.stackoverflow.com"]) //add more conditions here
    {
          [self callActionMethod];
    }
}
Run Code Online (Sandbox Code Playgroud)


iPr*_*abu 11

只要用户按下键,就会调用该代理

试试这个 :-

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([[textView.text stringByAppendingString:text] isEqualToString:@"a"])
    {
      //trigger 'a' operation
    }
    else if([[textView.text stringByAppendingString:text] isEqualToString:@"do it"])
    {
      //trigger do it operation
    }
    //Same conditions go on
}
Run Code Online (Sandbox Code Playgroud)

  • 您不能只是附加文本,您必须考虑更改发生的位置范围. (2认同)

Dev*_*t10 8

使用Swift 3解决方案

首先,添加 UITextViewDelegate

然后,viewDidLoad像这样设置委托,self.testTextField.delegate = self

最后,调用函数textViewDidChange,例如下面的例子.

func textViewDidChange(_ textView: UITextView) {
    // Do the logic you want to happen everytime the textView changes
    // if string is == "do it" etc....

}
Run Code Online (Sandbox Code Playgroud)


Kul*_*eep -14

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
    NSString * length;   
    NSString *currentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
length = [currentString length];
if (length > 1)
{

    looprange = _looptext.text;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please ! "
                                        message:@"Insert Single Characters !!"
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    return NO;

}
}
Run Code Online (Sandbox Code Playgroud)

  • -1; 该问题明确要求检测“UITextView”上的内容更改,而不是“UITextField”。这是错误的,我不知道提问者为什么接受它。正如其他答案中提到的,“UITextViewDelegate”中的类似方法是“- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text”(两者都可能不适合提问者的用例;请参阅http://stackoverflow.com/questions/7010547/uitextfield-text-change-event)。 (8认同)
  • -1 同意@MarkAmery 关于此处答案无关紧要的观点。 (2认同)