Ios 如何为UIgestureRecognitor操作传递参数
我想检测是否触摸了我的Ios 如何为UIgestureRecognitor操作传递参数,ios,iphone,textfield,Ios,Iphone,Textfield,我想检测是否触摸了我的UITextField。我用它来检测触摸: [self.myTextField addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTapped)]]; 我有一个方法 - (void)textFieldTapped:(UITextField *)textField { NSLog(@"is Tapped"); } 我想
UITextField
。我用它来检测触摸:
[self.myTextField addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTapped)]];
我有一个方法
- (void)textFieldTapped:(UITextField *)textField {
NSLog(@"is Tapped");
}
我想使用@selector(textfieldtaped)
将UITextField
添加为一个参数,但出现了一个错误。最好的方法是什么
[self.myTextField addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textFieldTapped:)]];
选择器名称末尾缺少冒号
编辑:操作应该如下所示
-(void)textFieldTapped : (UIGestureRecognizer*)rec{
NSLog(@"is Tapped");
}
目标操作选择器可能采用1个参数,表示此邮件的发件人。您可以添加冒号来发送消息,但不能将
UITextField
作为参数,而只能将发送者(这里是UITapGestureRecognizer)作为参数。是这样的:
[self.myTextField addgesturecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textfieldtaped:)]
如果您想了解有关文本字段的一些详细信息,可以使用UITapGestureRecognitizer的视图
属性
UITextField*tf=(UITextField*)gr.view
只需稍加修改即可
[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.
}
虽然您收到的错误是由于在
@selector(textfieldtapched)
中未包含textfieldtapched
之后的冒号,但即使使用冒号,您的代码也无法按预期工作。这是因为uigesturecognizer
操作方法只接受uigesturecognizer
作为参数;如果将uigesturecognizer
的目标设置为@selector(textfieldtrack:)
,则只要方法指示它接受它作为参数,就会自动传递uigesturecognizer
。例如(对于UITapGestureRecognitor
):
然后,要确定触摸了哪个UITextField
,可以使用以下方法获取textfield中的UITextField
对象:
UITextField *textField = (UITextField*)gesture.view;
但是在这种特殊情况下,根本不需要创建手势识别器,因为已经有了一个合适的UITextField
委托方法来检测UITextField
中的触摸。将uitextfield委托添加到.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;
}
UITextField
委托方法已可用。为什么要使用uitAppgestureRecognitizer
?请查看我的答案@user2951348以获得完整的解释。这是答案,但传递到textField的参数点击:
不是UITextField
,而是uidgestureRecognitizer
。我如何获取所接触的textField?UITextField*textField=(UITextField*)记录视图;请查看我的答案@user2951348以获得完整的解释。
UITextField *textField = (UITextField*)gesture.view;
// 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;
}