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

时间:2012-03-21 05:46:06

标签: iphone objective-c ios uitextview

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

例如:(在UITextView NOT UITextField中)

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

由于

4 个答案:

答案 0 :(得分: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];
    }
}

答案 1 :(得分:10)

只要用户按下

,就会调用此委托

试试这个: -

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

答案 2 :(得分: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....

}

答案 3 :(得分:-12)

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

}
}