UITextInputDelegate methods not functioning correctly

前端 未结 2 1308
故里飘歌
故里飘歌 2020-12-31 08:04

I\'m working on iOS 8 custom keyboard extension right now, and there are some issues in using UITextInputDelegate Methods.

Does this right: selectionWil

相关标签:
2条回答
  • 2020-12-31 08:45

    It's not working for me either... what I am currently doing is just using textWillChange and textDidChange which does get called, as you mentioned, when you change your selection... (they get called BEFORE and AFTER)

    And then comparing the:
    self.textDocumentProxy.documentContextBeforeInput
    self.textDocumentProxy.documentContextAfterInput

    From BEFORE (textWillChange) to the AFTER (textDidChange) to see if selection range or length changed at all.


    Something like this (set the 4 NSStrings below in your .h file of course... haven't tested this exact snippet because I wrote it from scratch just now on SO.com but I'm sure the principle works if I made any errors)

    - (void)textWillChange:(id<UITextInput>)textInput {
        beforeStringOfTextBehindCursor = self.textDocumentProxy.documentContextBeforeInput;
        beforeStringOfTextAfterCursor = self.textDocumentProxy.documentContextAfterInput;
    }
    
    - (void)textDidChange:(id<UITextInput>)textInput {
        afterStringOfTextBehindCursor = self.textDocumentProxy.documentContextBeforeInput;
        afterStringOfTextAfterCursor = self.textDocumentProxy.documentContextAfterInput;
    
        BOOL didSelectionChange = NO;
    
        if (![beforeStringOfTextBehindCursor isEqualToString:afterStringOfTextBehindCursor]) {
            didSelectionChange = YES;
        }
    
        if (![beforeStringOfTextAfterCursor isEqualToString:afterStringOfTextAfterCursor]) {
            didSelectionChange = YES;
        }
    
        if (didSelectionChange) {
            NSLog(@"Selection Changed!");
        }   
    }
    
    0 讨论(0)
  • 2020-12-31 09:01

    I had the same problem with the functions specified in the UITextInput protocol not being called. The reason as far as I can discern is due to the fact that the inputDelegate is set at runtime. According to the ios docs:

    The UIKit provides a private text input delegate, which it assigns at runtime to the inputDelegate property of the object whose class adopts the UITextInput protocol. link

    The fix which works in my case is to reset the inputDelegate in the function:

    textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
         replacementString:(NSString *)string
    

    by the following line:

    [myUITextField setInputDelegate:self];
    

    where self implements the UITextInputDelegate protocol.

    0 讨论(0)
提交回复
热议问题