简体   繁体   English

如何将UILongPressGestureRecognizer添加到UITextField?

[英]How to add a UILongPressGestureRecognizer to a UITextField?

I'm trying to add a UILongPressGestureRecognizer to a UITextfield; 我正在尝试将UILongPressGestureRecognizer添加到UITextfield; however, I can't seem to get it to behave properly. 但是,我似乎无法使其正常运行。 What I want is to override the default long press behavior (the magnifying glass and the option to "paste"), but also keep the ability to tap in the textfield in order to type in it. 我想要的是覆盖默认的长按行为(放大镜和“粘贴”选项),而且还要保持点击文本字段的能力,以便在其中键入内容。 With the code below, it still brings up the magnifying glass and even though it enters the textFieldLongPressed method, it never has the correct state. 使用下面的代码,它仍然会弹出放大镜,即使它输入了textFieldLongPressed方法,也永远不会具有正确的状态。 Any ideas? 有任何想法吗?

- (void) addLongPressRecognizer: (UIView *) view
{
    UILongPressGestureRecognizer *gestureRecognizer = [[UILongPressGestureRecognizer alloc] init];
    [gestureRecognizer addTarget:self action:@selector(textFieldLongPressed:)];
    gestureRecognizer.delegate = self;
    [view addGestureRecognizer: gestureRecognizer];
    self.myGestureReconginzer = gestureRecognizer;
}

- (void) textFieldLongPressed:(UILongPressGestureRecognizer*)sender 
{
    if (sender.state == UIGestureRecognizerStateBegan) 
    {
        [self.delegate textFieldLongPressed:self];
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if(gestureRecognizer == self.myGestureReconginzer)
    {
        //I've tried it with and without the following line
     // [self textFieldLongPressed:(UILongPressGestureRecognizer*) gestureRecognizer];
        return YES;
    }
    else if([gestureRecognizer class] == [UILongPressGestureRecognizer class])
    {
        return NO;
    }
    return YES;
}

Try adding something like this to your UITextField subclass: 尝试将以下内容添加到您的UITextField子类中:

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

This should disable the option to paste. 这应该禁用粘贴选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM