我有一个文本字段,当我按时,我想给它操作。
我尝试了两件事: 1)在TouchUpInside时给它动作。
[_countryTF addTarget:self action:@selector(testing:) forControlEvents:UIControlEventTouchUpInside];
和
-(IBAction)testing:(id)sender
{
NSLog(@"testing");
}
但是测试动作没有被调用。
2)我试图用这些通知来处理它
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHideHandler:)
name:UIKeyboardWillShowNotification
object:nil];
和
- (void) keyboardWillHideHandler:(NSNotification *)notification {
//show another viewcontroller here
NSLog(@"%@",notification.userInfo);
}
但是我没有获得有关谁发起通知的任何信息,因此我可以针对我的特定UITextField而不是任何其他UITextField进行操作。
所有想法?
答案 0 :(得分:2)
您应该使用UIGestueRecognizer。 textFieldDidBeginEditing:方法将在您第一次按文本字段时起作用。在您的文本字段中添加点击手势识别器:
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(testing:)];
[tapRecognizer setNumberOfTapsRequired:1];
[textField addGestureRecognizer:tapRecognizer];
现在您需要手动处理显示键盘。将此代码添加到您的测试:方法:
-(IBAction)testing:(id)sender
{
UITapGestureRecognizer *gr = (UITapGestureRecognizer*)sender;
UITextField *tf = (UITextField*)[gr view];
[tf becomeFirstResponder];
NSLog(@"testing");
}
答案 1 :(得分:1)
利用UITextField Delegate methods
。将textfield的委托设置为视图控制器类并实现此方法
- (void)textFieldDidBeginEditing:(UITextField *)textField // Tells the delegate that editing began for the specified text field.
答案 2 :(得分:0)
您也可以尝试:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHideHandler:)
name:UIKeyboardWillShowNotification
object:myTextField];
通过以下方式访问通知中的textField:
- (void) keyboardWillHideHandler:(NSNotification *)notification {
UITextField *textField = notification.object;
}
这只会处理第一次点击。 textField突出显示并显示键盘后,触摸后将不会注册。如果您只想对触摸做出初步反应,这是一个选项。否则,您应该使用像Greg解释的UITapGestureRecognizer。