How to disable copy paste option from UITextField programmatically

这一生的挚爱 提交于 2019-11-26 13:04:22
PengOne

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];
}

For iOS8.0+, Xcode 6.0.1, ARC enabled

Hoping to save a beginner, like myself, some time implementing this...

To implement disabling copy/paste/cut/etc. you must subclass UITextField and override...

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender

To do this...

Create a new class that is a subclass of UITextField (i.e. a new .h and .m files to be included within your app folder). So File->New->"Cocoa Touch Class"->Next->"PasteOnlyUITextField" (for example), subclass of "UITextField"->Next->Create.

Once the .h and .m files are created for our new subclass of UITextField called "PasteOnlyUITextField"...

PasteOnlyUITextField.h

#import <UIKit/UIKit.h>

@interface PasteOnlyUITextField : UITextField

@end

PasteOnlyUITextField.m

#import "PasteOnlyUITextField.h"

@implementation PasteOnlyUITextField

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(paste:))
    {
        return true;
    }

    return false;
}

@end

Now make sure you import PasteOnlyUITextField.h where you are going to use it, e.g. YourUIViewController.h file...

#import "PasteOnlyUITextField.h"

Now you must use the subclass, either progrommatically or with identity inspector

PasteOnlyUITextField *pasteOnlyUITextField = [[PasteOnlyUITextField alloc] init...];

or...

Select the UITextField and go to the identity inspector, select its class.

You can change the logic associated with the menu options as you see fit...

Hope this helps! Thanks to all the original contributors.

dtissera

I have found a way with swift using extension and associatedObject without subclassing. I use a property readonly to disable paste/cut but this sample can be adapted.

Swift 3 updated as of 27/11/2016

var key: Void?

class UITextFieldAdditions: NSObject {
    var readonly: Bool = false
}

extension UITextField {
    var readonly: Bool {
        get {
           return self.getAdditions().readonly
     } set {
        self.getAdditions().readonly = newValue
    }
}

private func getAdditions() -> UITextFieldAdditions {
    var additions = objc_getAssociatedObject(self, &key) as? UITextFieldAdditions
    if additions == nil {
        additions = UITextFieldAdditions()
        objc_setAssociatedObject(self, &key, additions!, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
    }
    return additions!
}

open override func target(forAction action: Selector, withSender sender: Any?) -> Any? {
    if ((action == #selector(UIResponderStandardEditActions.paste(_:)) || (action == #selector(UIResponderStandardEditActions.cut(_:)))) && self.readonly) {
        return nil
    }
    return super.target(forAction: action, withSender: sender)
}

}

Other Swift (2.2)

import UIKit

var key: Void?

class UITextFieldAdditions: NSObject {
    var readonly: Bool = false
}

extension UITextField {
    var readonly: Bool {
        get {
            return self.getAdditions().readonly
        }
        set {
            self.getAdditions().readonly = newValue
        }
    }

    private func getAdditions() -> UITextFieldAdditions {
        var additions = objc_getAssociatedObject(self, &key) as? UITextFieldAdditions
        if additions == nil {
            additions = UITextFieldAdditions()
            objc_setAssociatedObject(self, &key, additions!, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
        }
        return additions!
    }

    public override func targetForAction(action: Selector, withSender sender: AnyObject?) -> AnyObject? {
        if ((action == Selector("paste:") || (action == Selector("cut:"))) && self.readonly) {
            return nil
        }
        return super.targetForAction(action, withSender: sender)
    }

}

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

Himani Sharma

Implement this Method in ViewController.m This Method will help you to disable Options on UITextField.

It Includes paste, select, selectAll and copy option on your Corresponding UITextField.

This method is very useful in case of UITextField when you want to take this for Password or DateOfBirth or whatever you want.

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if ((_TextField1 isFirstResponder] || [_TextFied2 isFirstResponder]) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
        }];
    }
    return [super canPerformAction:action withSender:sender];
}
Himanshu Sraswat

In iOS 9 we can hide the copy paste bar from keyboard

-(void) customMethod{

   yourTextField.inputAssistantItem.leadingBarButtonGroups = @[];
   yourTextField.inputAssistantItem.trailingBarButtonGroups = @[];

}
Raginmari

Small update of this answer for iOS 10 and earlier (Swift 3):

open override func target(forAction action: Selector, withSender sender: Any?) -> Any? {
    guard isReadonly else {
        return super.target(forAction: action, withSender: sender)
    }

    if #available(iOS 10, *) {
        if action == #selector(UIResponderStandardEditActions.paste(_:)) {
            return nil
        }
    } else {
        if action == #selector(paste(_:)) {
            return nil
        }
    }

    return super.target(forAction: action, withSender: sender)
}

NOTE: In Swift, If you want your text field to disable all UIResponderStandardEditActions (cut, copy, paste, look up, share, select), use this is UITextFieldDelegate.

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    textField.isUserInteractionEnabled = false
    return true
}

func textFieldDidEndEditing(_ textField: UITextField) {
    textField.isUserInteractionEnabled = true
}

If disabled text selection works for you, try this.

class NoMoreSelectionTextField: UITextField {

    override func caretRect(for position: UITextPosition) -> CGRect {
        return CGRect.zero
    }

    override var selectedTextRange: UITextRange? {
        get { return nil }
        set { return }
    }
}

Try this in your viewController

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
        }];
        return [super canPerformAction:action withSender:sender];
    }

you can extension textview or textfield in swift, like this:

extension UITextView {    
    open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    return false
    }
}

Swift 5 solution:

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if action == #selector(UIResponderStandardEditActions.copy(_:)) || action == #selector(UIResponderStandardEditActions.paste(_:)) {
        return false
    }

    return true
}

Overriding targetForAction:withSender is best IMHO:

- (id)targetForAction:(SEL)action withSender:(id)sender
{
    if (action == @selector(paste:)) {
        return nil;
    }
    return [super targetForAction:action withSender:sender];
}

Swift 3.0 version

class NoMenuTextField: UITextField {
    override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        if (action == #selector(NSObject.paste(_:))) {
            return false
        }
        return super.canPerformAction(action, withSender: sender)
    }
}

use for iOS 7 or later

 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
}];
return [super canPerformAction:action withSender:sender];

}

Just set userInteractionEnabled = NO;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!