简体   繁体   中英

How to detect tap on UITextField?

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.

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.

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

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

  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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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