UITextField text change event

后端 未结 21 1039
南方客
南方客 2020-11-22 06:49

How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly.

21条回答
  •  悲&欢浪女
    2020-11-22 07:22

    You should use the notification to solve this problem,because the other method will listen to the input box not the actually input,especially when you use the Chinese input method. In viewDidload

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)
                                                     name:@"UITextFieldTextDidChangeNotification"
                                                   object:youTarget];
    

    then

    - (void)textFiledEditChanged:(NSNotification *)obj {
    UITextField *textField = (UITextField *)obj.object;
    NSString *toBestring = textField.text;
    NSArray *currentar = [UITextInputMode activeInputModes];
    UITextInputMode *currentMode = [currentar firstObject];
    if ([currentMode.primaryLanguage isEqualToString:@"zh-Hans"]) {
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        if (!position) {
            if (toBestring.length > kMaxLength)
                textField.text =  toBestring;
    } 
    

    }

    finally,you run,will done.

提交回复
热议问题