Как определить пользовательский символ ввода в UITextView
Как определить входной символ пользователя в UITextView?
Например: (в UITextView NOT UITextField)
когда пользователь вводит букву "a", запускает событие. когда пользователь вводит "делать это", запускает другое событие.
или ввод "http://www.stackoverflow.com" инициирует событие.
Спасибо
Ответы
Ответ 1
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString* [email protected]"";
parameterStr=[[textField text] stringByAppendingString:string];
if([parameterStr isEqualToString:@"do it"] || [parameterStr isEqualToString:@"http://www.stackoverflow.com"] || [parameterStr isEqualToString:@"a"])
{
return YES;
}
else
{
return NO;
}
}
Ответ 2
Вы можете отслеживать изменения содержимого 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];
}
}
Ответ 3
Этот делегат будет вызываться всякий раз, когда пользователь нажимает клавишу
Попробуйте следующее: -
- (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
}
Ответ 4
Рабочее решение Swift 3
Сначала добавьте UITextFieldDelegate
Затем установите делегат в 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....
}