ios 如何检测 UITextField 上的点击?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18729523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:04:24  来源:igfitidea点击:

How to detect tap on UITextField?

iosobjective-ccocoa-touch

提问by Josue Espinosa

I have a UITextField that has User Interaction Disabled. So if you tap on this text field, nothing happens. Normally to check if a text field was tapped Id try the delegate methods, but I cannot because user interaction is disabled. Is there any way I can check if the text field was tapped/touched? I change another element to hidden = no; when it is tapped so I was wondering if its even possible enabling user interaction.

我有一个禁用用户交互的 UITextField。因此,如果您点击此文本字段,则不会发生任何事情。通常检查文本字段是否被点击 Id 尝试委托方法,但我不能因为用户交互被禁用。有什么方法可以检查文本字段是否被点击/触摸?我将另一个元素更改为 hidden = no; 当它被点击所以我想知道它是否甚至可能启用用户交互。

回答by Grzegorz Krukowski

Best option is to turn on User Interaction and disable edit action using delegate method.

最好的选择是使用委托方法打开用户交互并禁用编辑操作。

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
     return NO;
} 

You can call your method inside that function to detect tap.

您可以在该函数内调用您的方法来检测点击。

回答by Camo

Maybe, you can add UITapGestureRecognizerin the superview, detect if the touch is inside the frame, and then do something.

也许,你可以UITapGestureRecognizer在superview中添加,检测触摸是否在框架内,然后做一些事情。

Detect touch if it is inside the frame of the super view

检测触摸是否在超级视图的框架内

  1. Create UITapGestureRecognizerand add that to the UITextField's super view.
  2. Implement the target selector and check if the gesture's state has ended.
  3. Call your method.
  1. 创建UITapGestureRecognizer并将其添加到UITextField的超级视图。
  2. 实现目标选择器并检查手势的状态是否已结束。
  3. 调用你的方法。

Objective-C

目标-C

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didRecognizeTapGesture:)];
[self.textField.superview addGestureRecognizer:tapGesture];


- (void) didRecognizeTapGesture:(UITapGestureRecognizer*) gesture {
    CGPoint point = [gesture locationInView:gesture.view];

    if (gesture.state == UIGestureRecognizerStateEnded) {
        if (CGRectContainsPoint(self.textField.frame, point)) {
            [self doSomething];
        }
    }
}

Swift 3

斯威夫特 3

func viewDidLoad() {
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didRecognizeTapGesture(_:)))

    textField.superView?.addGestureRecognizer(tapGesture)
}

private dynamic func didRecognizeTapGesture(_ gesture: UITapGestureRecognizer) {
    let point = gesture.location(in: gesture.view)

    guard gesture.state == .ended, textField.frame.contains(point) else { return }

    //doSomething()
}