如何检测UITextField上的点击? [英] How to detect tap on UITextField?

查看:117
本文介绍了如何检测UITextField上的点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

也许,你可以添加 UITapGestureRecognizer 在超级视图中,检测触摸是否在帧内,然后执行某些操作。

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


  1. 创建 UITapGestureRecognizer 并将其添加到 UITextField 的超级视图。

  2. 实现目标选择器并检查手势的状态是否已经结束。

  3. 打电话给你的方法。

  1. Create UITapGestureRecognizer and 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.



Objective-C



Objective-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



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

这篇关于如何检测UITextField上的点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆