简体   繁体   中英

How to test if User has changed UITextInput?

I'm developing a custom keyboard for iOS, using the UIInputViewController I have implemented the following methods: textWillChange , textDidChange .

I want to know when user changes the current text field and moves to another one in order to configure the Auto Capitalization parameters of the currently pressed text field in the keyboard.

Now I tried to do something like this:

override func textWillChange(textInput: UITextInput) {
    if !textInput.isEqual(self.mCurrentTextInput) {
        Logger.printLogToConsole(TAG, aMethodName: __FUNCTION__, aMessage: "TextInput has changed!")
        KeyboardState.sharedInstance.setAutoCapitalizationFlag()
    }
    self.mCurrentTextInput = textInput
}

Or even something like this:

override func textWillChange(textInput: UITextInput) {
     if self.mCurrentTextInput == nil {
        if let view = textInput.textInputView {
            self.mCurrentTextInput = view
            KeyboardState.sharedInstance.setAutoCapitalizationFlag()
        }
        Logger.printLogToConsole(TAG, aMethodName: __FUNCTION__, aMessage: "TextInput has changed!")
    } else if self.mCurrentTextInput!.isEqual(textInput) {
        Logger.printLogToConsole(TAG, aMethodName: __FUNCTION__, aMessage: "TextInput has changed!")
        if let view = textInput.textInputView {
            KeyboardState.sharedInstance.setAutoCapitalizationFlag()
            self.mCurrentTextInput = view
        }
    }
}

But none of those options works for me.

UPDATE: As you can notice the object I receive in the callback methods is not a UITextField object but a UITextInput object which is actually a protocol, and not the text field itself. So I can't add observer to it. My keyboard application does not control the fields the user enters text into.

Question: how can I recognize the moment that the user changes his current text field?

I am using Objective C, as I have this code available at this point of time:-

You can use KVO , I guess for your objective:-

static void *contextNew = &contextNew;

//Observe change to txtfeild.text:

[self.txtfeild addObserver:self forKeyPath:@"text"
            options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld 
            context:contextNew];


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
        change:(NSDictionary *)change context:(void *)context {

          if(context == contextNew) {

              NSLog(@"txtfeild new text : %@ - txtfeild Old text: %@",
              [change objectForKey:NSKeyValueChangeNewKey],
              [change objectForKey:NSKeyValueChangeOldKey]);
          }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM