如何传递UIGestureRecognizer操作的参数

时间:2014-03-04 10:32:10

标签: ios iphone textfield

我想检测我的UITextField是否被触及过。我用它来检测触摸:

[self.myTextField addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTapped)]];

我有一个方法

- (void)textFieldTapped:(UITextField *)textField {
    NSLog(@"is Tapped");
}

我想使用UITextField@selector(textFieldTapped)添加为参数但我收到错误。最好的方法是什么?

4 个答案:

答案 0 :(得分:1)

[self.myTextField addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTapped:)]];

你在选择器名称的末尾错过了冒号。

编辑:并且操作应该看起来像

-(void)textFieldTapped : (UIGestureRecognizer*)rec{
  NSLog(@"is Tapped");
}

答案 1 :(得分:0)

目标操作选择器可以使用1个arg,表示此消息的发件人。您可以添加冒号来发送邮件,但不能将UITextField作为参数,而只能将发件人(此处为UITapGestureRecognizer)作为参数。它会是这样的:

[self.myTextField addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTapped :));

-(void)textFieldTapped : (UITapGestureRecognizer *)gr{
    NSLog(@"is Tapped");
}

如果您想了解有关文本字段的一些详细信息,可以使用UITapGestureRecognizer的view属性

UITextField *tf = (UITextField *)gr.view

答案 2 :(得分:0)

只需要做一点修改

[self.myTextField addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTapped:)]];

和方法将是

-(void)textFieldTapped : (UITapGestureRecognizer *)recognizer
{
    UITextField *tappedTextField=(UITextField *)[[recognizer self] view]; // this is the textfield that is being tapped.
    //You can access all the property associated with the textField.
}

答案 3 :(得分:0)

虽然您收到的错误是textFieldTapped @selector(textFieldTapped)之后不包括冒号的结果,即使使用冒号,您的代码也无法正常工作。这是因为UIGestureRecognizer操作方法仅接受UIGestureRecognizer作为参数;如果将UIGestureRecognizer的目标设置为@selector(textFieldTapped:),则UIGestureRecognizer本身会自动传递,只要方法表明它接受它作为参数即可。防爆。 (在UITapGestureRecognizer的情况下):

- (void)textFieldTapped:(UITapGestureRecognizer*)gesture {
    NSLog(@"is Tapped");
}

然后,要找出触摸了哪个UITextField,您可以使用以下方法获取UITextField方法中的textFieldTapped:对象:

UITextField *textField = (UITextField*)gesture.view;

但在这种特殊情况下,根本不需要创建手势识别器,因为已经有适当的UITextField委托方法来检测UITextField中的触摸。将UITextFieldDelegate添加到.h并设置theParticularTextField.self = delegate后,我建议使用:

// Called whenever a text field is selected as long as its delegate is set to self
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {

    if (textField == theParticularTextField) {
        // Do whatever you want to do when that particular text field is tapped.
    }

    return YES;
}