UITextView Delegates Behaving Differently with Custom iOS Keyboards (SwiftKey)

223 views Asked by At

Using the shouldChangeTextInRange delegate to detect certain phrases when typed in a UITextViewgives different range and text values when alternating between the stock keyboard and custom keyboards like SwiftKey (in identical scenarios).

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {...}

For example:

The moment after I type: "ABCDEFG HIJ " without quotes and including the ending space using the stock keyboard, I find the range is equal to (11, 0). However, with SwiftKey, I'm getting a range of (10, 1). Additionally, the text will be equal to just the ending space using the stock keyboard, but will be equal to 'J' plus the space using SwiftKey. Any ideas why this is happening and how I can standardize my function's behavior given these differences if I want to properly detect certain phrases? (my goal is detecting the two words immediately before every space press)

EDIT: this is how I detect the two words in front of a space. My issue is that range is giving me different values when I use a non-stock keyboard

            NSUInteger charsBackUntilSecondSpace = 0;
            NSUInteger numSpacesFound = 0;
            for (int i = (int) range.location - 1; i>= 0; i--) {
                if([textView.text characterAtIndex:i] == ' ') {
                    numSpacesFound++;
                }
                if (numSpacesFound == 2) {
                    break;
                }
                else {
                    charsBackUntilSecondSpace++;
                }
            }

            UITextRange *selectedTextRange = textView.selectedTextRange;
            NSUInteger location = [textView offsetFromPosition:textView.beginningOfDocument
                                                    toPosition:selectedTextRange.start];
            NSRange inFrontOfCursorRange = NSMakeRange (location - charsBackUntilSecondSpace, charsBackUntilSecondSpace);
1

There are 1 answers

1
Hussain Shabbir On

my goal is detecting the two words immediately before every space press

You can achieve it like that below:-

NSInteger lenPos=(range.length > 2) ? 2 : range.length;
NSString *txt=[textView.text substringWithRange:NSMakeRange(range.length-lenPos-1, lenPos)] ;