Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable copy paste option from UITextField programmatically

I am making a registration alertview that has a UITextField in it where the user can enter their registration number. everything is pretty much their, however I would like to remove the copy paste function from the textfield programmatically since their is no InterfaceBuilder version of the textfield I have no idea how to do this..

here Is my UIalertview thus far...

- (void)pleaseRegisterDevice {      UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Please Register Device!" message:@"this gets covered" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];     regTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];     [regTextField setBackgroundColor:[UIColor whiteColor]];     regTextField.textAlignment = UITextAlignmentCenter;     [myAlertView addSubview:regTextField];     [myAlertView show];     [myAlertView release];  } 
like image 211
C.Johns Avatar asked Jul 14 '11 23:07

C.Johns


2 Answers

This post has many nice solutions: How disable Copy, Cut, Select, Select All in UITextView

My favourite is to override canPerformAction:withSender::

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {     if (action == @selector(paste:))         return NO;     return [super canPerformAction:action withSender:sender]; } 
like image 105
PengOne Avatar answered Oct 04 '22 01:10

PengOne


Storyboard users may want to look at this solution, as long as you are ok with subclassing.

I don't think that there is an easy way to achieve this through extensions or protocols.

Swift 3.1

import UIKit  @IBDesignable class CustomTextField: UITextField {      @IBInspectable var isPasteEnabled: Bool = true      @IBInspectable var isSelectEnabled: Bool = true      @IBInspectable var isSelectAllEnabled: Bool = true      @IBInspectable var isCopyEnabled: Bool = true      @IBInspectable var isCutEnabled: Bool = true      @IBInspectable var isDeleteEnabled: Bool = true      override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {         switch action {         case #selector(UIResponderStandardEditActions.paste(_:)) where !isPasteEnabled,              #selector(UIResponderStandardEditActions.select(_:)) where !isSelectEnabled,              #selector(UIResponderStandardEditActions.selectAll(_:)) where !isSelectAllEnabled,              #selector(UIResponderStandardEditActions.copy(_:)) where !isCopyEnabled,              #selector(UIResponderStandardEditActions.cut(_:)) where !isCutEnabled,              #selector(UIResponderStandardEditActions.delete(_:)) where !isDeleteEnabled:             return false         default:             //return true : this is not correct             return super.canPerformAction(action, withSender: sender)         }     } } 

Gist link

like image 44
gujci Avatar answered Oct 04 '22 02:10

gujci