0

I want to use the UIMenuController to display autofill options for a textfield based on data I already have in my app. The code to update the menu items and fill the textfield when one is selected works fine, but I can't seem to find a way to keep the menucontroller visible while typing. I've tried

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];
    return YES;
}

but that does nothing. If I put the code to update the menu items before the code to set the menu visible I just end up replacing the first letter in the textfield over and over again and the menu still fails to show.

It's possible that the real problem to fix here is UIMenuController automatically selecting the last word in the text field when it shows, but I haven't found a fix for that either.

codemolly
  • 181
  • 6

1 Answers1

0

I have been trying to figure out a way to do the same. Assuming that your code displays the UIMenuController by making the view first responder, add the bit of code that makes the menu visible inside an operation block:

[[NSOperationQueue mainQueue] addOperationWithBlock:^{ [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES]; }];

This displays the menu and the text entered in the textfield. But the drawback is, the textfield is no longer the first responder. So the user has to tap again on the textfield to enter a new character. This is not very user friendly.

The other option for autocompletion is using a UITableView instead of UIMenuController like here: http://www.raywenderlich.com/336/auto-complete-tutorial-for-ios-how-to-auto-complete-with-custom-values

But UIMenuController is cleaner. I have tried many approaches to make UIMenuController my winner, but I have failed to optimise this approach. If you have found a solution, please let me know.

Koushik Ravikumar
  • 664
  • 11
  • 26
  • I ended up going a different route that takes up less real estate and actually looks really great. Check out [this Autocomplete Text Field](https://github.com/hoteltonight/HTAutocompleteTextField) posted by Jon Sibley at HotelTonight. – codemolly Dec 12 '14 at 21:43
  • Yes, the alternatives to UIMenuController are way more attractive. – Koushik Ravikumar Dec 17 '14 at 10:56