如何检测UITextField的点击?
我有一个用户交互禁用的UITextField。 所以如果你点击这个文本字段,什么都不会发生。 通常要检查文本字段是否被点击Id尝试委托方法,但我不能因为用户交互被禁用。 有什么方法可以检查文本字段是否被轻敲/触摸? 我改变另一个元素隐藏=否; 当它被挖掘,所以我想知道,如果它甚至可能的使用户交互。
也许,你可以在UITapGestureRecognizer
视图中添加UITapGestureRecognizer
,检测触摸是否在框架内,然后做一些事情。
检测触摸,如果它在超级视图的框架内
- 创build
UITapGestureRecognizer
并将其添加到UITextField
的超级视图。 - 实现目标select器并检查手势的状态是否已经结束。
- 调用你的方法。
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() }
最好的select是打开用户交互,并使用委托方法禁用编辑操作。
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { return NO; }
您可以在该function内调用您的方法来检测点按。