How do Prevent a copy/paste/select popover on a UI

2019-04-17 04:21发布

The question: How do I prevent the copy/paste/select popup that occurs over a UITextView from appearing (not using UIwebView and css)?

I did not want to go the rout of UIWebView as some posts have gone because I already am using UIViews with UITextFields for data entry. I had tried unsuccessfully to implement the solutions dealing with UITextField in my implementation file of my view controller with the methods: targetForAction:withSender, setMenuVisible:animated and finally canPerformAction:withSender. (It NO WORKY WORKY - [sad face])

2条回答
贪生不怕死
2楼-- · 2019-04-17 04:27

If the UITextView is created as an object on a storyboard, the solution is even easier. In Attributes Inspector for the UITextView object, under Behavior, uncheck Editable and uncheck Selectable. Under the Scroll View section, you can check Scrolling Enabled if you want the user to be able to scroll text.

查看更多
唯我独甜
3楼-- · 2019-04-17 04:31

Ok, I found a working solution (in Xcode 5.1) to my question which, in short, is subclassing the UITextField.

I realized I wasn't really overriding the default behavior of the UITextField in the view controller like I wanted to and neither was putting the methods listed here override the behavior of the textfield delegate in the view controller file. The Key was to subclass the UITextField itself with -targetForAction:withSender. (I know some of you are screaming at the screen about how OBVIOUS that was!) It was not obvious to me. Like most problems when first figuring them out I went through a lot of different paths some I found here in SO. But the solution is a simple one. I want to share this solution in its own area so hopefully it can help someone out.

The header file:

//
//

#import <UIKit/UIKit.h>

@interface TPTextField : UITextField

- (id)targetForAction:(SEL)action withSender:(id)sender;
@end

and the implementation file (.m)

//
//

#import "TPTextField.h"

@implementation TPTextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
#pragma mark - method overrides - deny user copy/paste on UITTextFields
- (id)targetForAction:(SEL)action withSender:(id)sender
{
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    if (action == @selector(selectAll:) || action == @selector(paste:) ||action == @selector(copy:) || action == @selector(cut:)) {
        if (menuController) {
            [UIMenuController sharedMenuController].menuVisible = NO;
        }
        return nil;
    }
    return [super targetForAction:action withSender:sender];
}

@end

In your storyboard or nib/xib file just connect this class to your UITextfield like the picture below:

Custom Class:TPTextfield

I have it on git to for easy access here. Please let me know if this is helpful to you!

Tony

查看更多
登录 后发表回答