ios - 单击第二个文本字段时键盘未隐藏

标签 ios iphone swift

<分区>

我有两个文本字段。单击时,第一个显示 qwerty 键盘,第二个显示选择器。 我的问题是当我点击我的第一个 textField 时,键盘显示正确。现在,在我输入任何内容后,我直接想点击第二个文本字段,它是显示选择器,键盘应该消失,但键盘仍然存在。 我想在单击第二个文本字段时立即隐藏键盘。

最佳答案

有两种方法可以实现这一点-

首先:使用 UITextFieldDelegate。 为了那个原因- 在您的 View Controller 的协议(protocol)列表中列出 UITextFieldDelegate,例如,

@interface ViewController : UIViewController <UITextFieldDelegate>

然后使您的 ViewController 符合 Textfield 的委托(delegate)以实现方法,如 textFieldDidBeginEditingtextFieldDidEndEditing:

所以,转到 viewDidLoad 方法并符合 UITextField 的协议(protocol),例如 -

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.firstTextField.delegate = self; //assuming your first textfield's 
                                         //name is firstTextField
   //Also give your first textfield a tag to identify later

    self.firstTextField.tag = 1;
}

现在,您已准备好实现委托(delegate)方法。但是,要首先实现您的目标,您需要获取一个 UITextField 实例以了解您何时在 firstTextField 中键入。因此,声明一个 UITextField 类型的属性。在界面文件中这样做 -

@property(nonatomic, strong) UITextField *currentTextField;

现在在 textFieldDidBeginEditing 委托(delegate)方法中,当您开始在其中输入时,将 firstTextField 实例分配给 currentTextField,例如 -

- (void)textFieldDidBeginEditing:(UITextField *)textField{
       if(textField.tag == 1){
           self.currentTextField = textField;
       }
}

之后,在 textFieldDidEndEditing 方法中,检查它是否是您从中出来的当前文本字段,然后关闭键盘,如-

-(void)textFieldDidEndEditing:(UITextField *)textField{
          if(textField.tag == 1){
              [self.currentTextField resignFirstResponder];
          }
          return YES;
     }

其次:可以使用UIResponder。由于 ViewControllers 继承自 UIResponder,您只需重写方法 - touchesBegan:withEvent 方法,例如 -

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
      [self.view endEditing:YES];// this will do the trick
}

在这种情况下,当您在文本字段外单击时,键盘应该会自动消失。

关于ios - 单击第二个文本字段时键盘未隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763982/

相关文章:

ios - 是否可以将选项卡栏的一页的操作连接到另一页?

iphone - EKEventStore 错误一次后无法保存事件

iphone - UITableViewController 不会执行 UIDeviceOrientationPortraitUpsideDown 方向

ios - 实现 UIPopoverBackgroundView 子类时出现乱码异常

ios - UI KeyboardWillShowNotification 中的栏按钮项目动画

iphone - 从互联网下载plist(数据库)?

ios - 逐渐提高 SpriteKit 中滚动背景的速度

ios - 如何仅在滚动缓慢时才更新 tableView?

arrays - 获取更短版本的 for 循环?

ios - 快速 JSONDecoder 不工作