当我只是触摸UITextField以外的任何地方时,如何解除键盘?

时间:2011-02-09 04:33:28

标签: iphone keyboard uitextfield numeric-keypad

您好 我的应用程序中有两个UITextFields,当我只是触摸除UITextFields之外的任何地方时想要关闭键盘 我怎么能这样做?

10 个答案:

答案 0 :(得分:24)

为此目的使用tochesBegin方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

  [yourFirstTextField resignFirstResponder];
  [yourSecondTextField resignFirstResponder];
}

你不需要任何其他东西。当你触摸视图中的任何地方时,两个textField都不需要知道哪个有焦点。当你触摸textField然后textField自己打开键盘。

答案 1 :(得分:11)

Ishu的答案很好。但我认为你也应该尝试:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

  [self.view endEditing:YES];
}

答案 2 :(得分:1)

您需要在后台创建自定义按钮,然后将其连接到IBAction上调用resignFirstResponder的{​​{1}}方法

像这样的事情 enter image description here

编辑:

因为您想以编程方式添加按钮而不是使用此代码

UITextField

然后在此之后添加控制器代码。

答案 3 :(得分:1)

点击按钮时,创建一个隐藏按钮,将其放在UITextField后面并向您的文本字段发送resignFirstResponder消息。

答案 4 :(得分:1)

使用委托,

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
 [textField resignFirstResponder];
 return YES;
}

您还可以在控制器中创建方法

 -(IBAction)editingEnded:(id)sender{
    [sender resignFirstResponder]; 
}

然后在IB连接检查器中连接事件“退出时已结束”。

答案 5 :(得分:1)

通常在这种情况下,您将拥有一个滚动视图,其中包含用户界面的其余部分。如果您将该滚动视图的委托分配给视图控制器,并说您实现了协议UIScrollViewDelegate,那么只需添加以下方法即可完成此任务:

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

答案 6 :(得分:0)

如果您没有使用“界面”构建器,则可以按照此处说明手动挂接事件: How can I programmatically link an UIView or UIImageView with an event like "touch up inside"?

如果您使用的是“界面”构建器,则无需创建背景按钮。

你可以这样做:

  1. 选择您的视图(可能称为View)
  2. 切换到属性检查器中的(i)选项卡
  3. 将班级从UIView更改为UIControl(这使您可以访问 Touch Down 事件。)
  4. Touch Down 事件挂钩到backgroundTap方法(按Ctrl +拖动)。
  5. 不要忘记保存更改

答案 7 :(得分:0)

You need to define the action for your button click this way

[infoButton addTarget:self action:@selector(backButtonClicked) forControlEvents:UIControlEventTouchUpInside];


And implement the click method ,as for example i have provided the animation on button click method.
-(void)backButtonClicked
{

    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:1.5];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:NO]; 
    [self.navigationController popViewControllerAnimated:YES]; 
    [UIView commitAnimations];

}


Hope this will help you ,the action is without using IB.Its all done through coding

答案 8 :(得分:0)

使用此功能。

- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{

    const int movementDistance = 180; distace of keyboard up.

    const float movementDuration = 0.3f;

     int movement = (up ? -movementDistance : movementDistance);

    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];

    [UIView setAnimationDuration: movementDuration];

    self.view.frame = CGRectOffset(self.view.frame, 0, movement);

    [UIView commitAnimations];
}

答案 9 :(得分:-1)

在视图控制器中保留对UITextField的引用并调用[yourTextField resignFirstResponder]