Disable the menu for a textfield

November 17th, 2011
#ui

I ran across the scenario where I wanted to disable the paste functionality on some textfield in my application. I've did this many times before and quickly added the following method to my viewcontroller:

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  
  if ([UIMenuController sharedMenuController]) {
    
    [UIMenuController sharedMenuController].menuVisible = NO;
    
  }
  
  return NO;
}

While the above method had the desired effort in iOS4.x, in iOS5 I was still presented with the option to paste.

Some further investigation lead me to the solution that I needed to include the exact same code in a subclass of UITextField and then use instances of that class, MenuDisabledTextField:

#import "MenuDisabledTextField.h"

@implementation MenuDisabledTextField

#pragma mark - Menu controls

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  
  if ([UIMenuController sharedMenuController]) {
    
    [UIMenuController sharedMenuController].menuVisible = NO;
    
  }
  
  return NO;
}

@end

What do you think? Let me know by getting in touch on Twitter - @wibosco