views:

45

answers:

1

Is there a way to implement custom Auto-completion for a UITextView, say by giving it a NSDictionary or NSArray of Strings to watch out for?

A: 

You would have to program it yourself. If you implement the UITextViewDelegate Protocol, the function

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *) 

is called every time the user enters / deletes a character in the text view. So for example if the user enters a char 's', then in this function you would check the array w the words you want to autocomplete to see if it should autocomplete.

CONDITIONS -

• If there is only one value that starts with 's', autocomplete.

• If there are no values that start with 's', or if there are multiple values that start with 's', (ELSE) do not autocomplete.

I recommend that your autocomplete string array is sorted alphabetically, and that you keep a global variable that points to where you left off in the array. For example if the user enters 's', and the first word with 's' is in array index 5, then when the user enters another char, 'u' making the search string "su", you should be able to remember to start in array index 5 to find the autocomplete string faster (and not iterate through useless data). I would use a C array for this, although an NSArray would work.

jmont
2 questions, Would that method work with a UITextView (as mentioned in my question) and how would I actually do the autcompletion. Thanks!
Joshua
I updated my answer. as far as the autocompletion goes, its harder with uitextview. you would have to find the last characters entered in the text view, and see if they can be autocompleted by checking them to every item in your string array with the conditions I outlined above. As I mentioned you can optimize your code to run faster if you don't make it iterate through the list every time. If you find that you can autocomplete just replace the substring entered with the autocompleted string.
jmont
Right, I see. Would you suggest I check the conditions by using `NSString`'s `characterAtIndex:` method when iterating through the array?
Joshua
Yes that's a good idea. There are other methods you can use (rangeOfString:) but they might be too complicated for this? Anyway remember that these functions are case sensitive ("C" != "c") so you might want to deal with that.
jmont