Using the shouldChangeTextInRange
delegate to detect certain phrases when typed in a UITextView
gives 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);
You can achieve it like that below:-