f0rz f0rz - 1 year ago 79
iOS Question

Confirm UITextview auto-complete

This seems impossible, but maybe someone else has had the same problem.

Is it possible for me to accept an autocomplete programmatically, or in some way get the suggested word that pops up? My problem is that I'm capturing the return/backspace keystroke and then move focus to another textview. When enter/backspace is hit, the textview will ignore the auto-suggested word. It seems that it is only possible to accept an autocompletion by hit space/dot (and return for new row). With this code:

- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
NSRange textViewRange = [textView selectedRange];

// Handle newrow and backspace.
if(([text length] == 0) && (textViewRange.location== 0) && textViewRange.length==0){
[delegate doSomethingWhenBackspace];
return NO;
}else if ([text isEqualToString:@"\n"]){
[delegate doSomethingWhenReturn];
return NO;

return YES;

I tried to programmatically add "space" when the return key is hit but that also ignores the auto-completed word.

else if ([text isEqualToString:@"\n"]){
// Tryin to accept autocomplete with no result.
textview.text = [textview.text stringByAppendingString:@" "];
[delegate doSomethingWhenReturn];
return NO;

Any suggestions?

Answer Source

I've had a very similar problem, I was making an app that had to read every letter in a text view and I has issues when Autocomplete inserted words because it was saving it as if it was one letter. you could add each character to an array and then check to see if any are over 1 string in length. Or you could add each character that is put in into an array and then run something like

NSString *string = text;
NSMutableArray *array = [NSMutableArray new];
for (int i=0; i<string.length; i++) {
 [array addObject:[string substringWithRange:NSMakeRange(i, 1)]];

to add each character individually, by comparing the two arrays you could determine if autocorrect has been used and with what word/s. Hope this will help.