【问题标题】:How to detect tap on UITextField?如何检测 UITextField 上的点击?
【发布时间】:2013-09-10 22:04:40
【问题描述】:

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

【问题讨论】:

  • 作为未来访问者的旁注:如果您想打开一个选择器来为您的 UITextField 选择一个值,请将选择器用作文本字段 inputView。当点击文本字段时,这将自动显示选择器而不是键盘。可选地使用 UIToolBar 作为文本字段 inputAccessoryView 然后显示在选择器上方(用于完成按钮等)。

标签: ios objective-c cocoa-touch


【解决方案1】:

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

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

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

【讨论】:

  • 也试过了,但我有其他文本字段,所以这不起作用。
  • 它有效 - 你只需要检查 if(textField == self.blockedTextField) return NO;否则返回YES;
  • 真的很奇怪 - 我经常使用它 - 你能用这种方法粘贴你的代码吗?
  • - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { if(textField ==birthdayTextField){birthdayDatePicker.hidden = NO;生日日期选择器.alpha = 0;返回否; } 其他{ 返回​​是; } }
  • Josue,您必须确保使用 textFieldShouldBeginEditing 方法将 UITextField 的委托设置为 UIViewController。
【解决方案2】:

也许,你可以在superview中添加UITapGestureRecognizer,检测触摸是否在框架内,然后做点什么。

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

  1. 创建UITapGestureRecognizer 并将其添加到UITextField 的超级视图中。
  2. 实现目标选择器并检查手势的状态是否已结束。
  3. 调用你的方法。

目标-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];
        }
    }
}

斯威夫特 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()
}

【讨论】:

  • 点击文本字段时不调用,仅在其外部调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多