如何以编程方式禁用 UITextField 中的复制粘贴选项

发布于 2024-11-24 03:26:11 字数 718 浏览 5 评论 0原文

我正在制作一个注册警报视图,其中有一个 UITextField,用户可以在其中输入他们的注册号。一切几乎都是他们的,但是我想以编程方式从文本字段中删除复制粘贴功能,因为它们不是文本字段的 InterfaceBuilder 版本,我不知道如何执行此操作..

这是迄今为止我的 UIalertview...

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

}

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

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

[浮城] 2024-12-01 03:26:11

这篇文章有很多不错的解决方案:如何禁用复制、剪切、选择,在 UITextView 中全选

我最喜欢的是重写 canPerformAction:withSender:

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

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];
}
日久见人心 2024-12-01 03:26:11

故事板用户可能想看看这个解决方案,只要您同意子类化即可。

我认为没有一种简单的方法可以通过扩展或协议来实现这一目标。

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)
        }
    }
}

要点链接

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

甩你一脸翔 2024-12-01 03:26:11

对于 iOS8.0+、Xcode 6.0.1,启用了 ARC

希望为像我这样的初学者节省一些时间实现此...

实现禁用复制/粘贴/剪切/等。您必须子类化 UITextField 并覆盖...

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

要执行此操作...

创建一个新类,该类是 UITextField 的子类(即要包含在应用程序文件夹中的新 .h 和 .m 文件) 。所以文件->新建->“Cocoa Touch Class”->下一步->“PasteOnlyUITextField”(例如),“UITextField”的子类->下一步->创建。

一旦为名为“PasteOnlyUITextField”的 UITextField 新子类创建了 .h 和 .m 文件...

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

现在请确保在您所在的位置导入 PasteOnlyUITextField.h要使用它,例如 YourUIViewController.h 文件...

#import "PasteOnlyUITextField.h"

现在您必须使用子类,无论是按编程方式还是使用标识检查器

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

或...

选择 UITextField 并转到身份检查器,选择其类。

identity Inspector

您可以根据需要更改与菜单选项关联的逻​​辑...

希望这有帮助!感谢所有原始贡献者。

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.

identity inspector

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

Hope this helps! Thanks to all the original contributors.

短叹 2024-12-01 03:26:11

我找到了一种快速使用扩展和关联对象而不需要子类化的方法。
我使用只读属性来禁用粘贴/剪切,但可以调整此示例。

Swift 3 截至 2016 年 11 月 27 日更新

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)
}

}

其他 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)
    }

}

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)
    }

}
乖乖 2024-12-01 03:26:11

在 Swift 中,如果您希望文本字段禁用所有 UIResponderStandardEditActions(剪切、复制、粘贴、查找、共享、选择),请在 UITextFieldDelegate 中使用它。

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

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

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

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

func textFieldDidEndEditing(_ textField: UITextField) {
    textField.isUserInteractionEnabled = true
}
滥情稳全场 2024-12-01 03:26:11

在 ViewController.m 中实现此方法此方法将帮助您禁用 UITextField 上的选项。

它包括相应 UITextField 上的粘贴、选择、全选和复制选项。

当您想将其用作密码或 DateOfBirth 或任何您想要的内容时,此方法在 UITextField 的情况下非常有用。

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

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];
}
花辞树 2024-12-01 03:26:11

在 iOS 9 中,我们可以隐藏键盘上的复制​​粘贴栏

-(void) customMethod{

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

}

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

-(void) customMethod{

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

}
╄→承喏 2024-12-01 03:26:11

斯威夫特 5 解决方案:

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

    return true
}

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
}
如果没有 2024-12-01 03:26:11

针对 iOS 10 及更早版本 (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)
}

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)
}
墟烟 2024-12-01 03:26:11

在你的 viewController 中尝试一下

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

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];
    }
猫弦 2024-12-01 03:26:11

禁用 UITextField 子类的所有操作。

import UIKit

class CustomTextField: UITextField {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}

Disable all actions by UITextField subclass.

import UIKit

class CustomTextField: UITextField {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        return false
    }
}
失而复得 2024-12-01 03:26:11

您可以在 swift 中扩展 textview 或 textfield,如下所示:

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

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

extension UITextView {    
    open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    return false
    }
}
茶花眉 2024-12-01 03:26:11

如果禁用文本选择适合您,请尝试此操作。

class NoMoreSelectionTextField: UITextField {

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

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

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 }
    }
}
半寸时光 2024-12-01 03:26:11

恕我直言,覆盖 targetForAction:withSender 是最好的:

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

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];
}
放低过去 2024-12-01 03:26:11

斯威夫特3.0版本

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)
    }
}

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)
    }
}
强者自强 2024-12-01 03:26:11

用于 iOS 7 或更高版本

 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
}];
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];

}

等待我真够勒 2024-12-01 03:26:11

只需设置 userInteractionEnabled = NO;

Just set userInteractionEnabled = NO;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文