I'm doing some custom auto-complete stuff on my own with insertText:
, but if there's an autocorrect suggestion visible the view gets into a weird state.
If I use [textView unmarkText]
, it dismisses the autocorrect popup thingy -- but it accepts the autocorrection (which is bad). Is there some way to programmatically reject the autocorrect suggestion?
My current "solution" works, but it's gross and hacky and I have no reason to assume it will continue to work in the future. Is there a better way to do this?
- (void)dismissAutocorrectSuggestionForTextView:(UITextView *)textView {
NSRange range = textView.selectedRange;
textView.text = textView.text;
textView.selectedRange = range;
}
Your original solution is close. Try the following:
Calling resign/become first responder back to back causes the text view to accept pending autocorrections immediately, but without actually dismissing the keyboard (try it you'll be surprised). This works on iOS 6 and iOS 7 for sure. After accepting the autocorrections, you then reset the text and the selected range to what they were prior to the autocorrections.
I just encountered this issue myself. This solution works well:
I tried something similar to yours, but setting the text of the textView this way results in the textView scrolling unnecessarily (my textView contains quite a bit of text). My solution involves restoring the contentOffset in an non-animated fashion. It's not exactly any more elegant than what you have, but at least it helps those who need to deal with longer text.
As for whether it'll continue to work in future, I've tried something like this since iOS 4, and it continues to work through iOS 6.
If resigning first responder from text view is unwanted and you can attach as a delegate to the text view, you could implement method
and
return NO
in a specific case. For example, you could try the following:When text view selection changes, autocompletion attempts to accept current suggestion, but text view consults this method before making replacements. An example of why would you do this instead of just resigning/becoming first responder is when you have some logic in
textViewDidBeginEditing
and/ortextViewDidEndEditing
methods, for example, which you don't want to be performed when you dismiss the autocorrection.