Ios 单击第二个文本字段时,键盘未隐藏

Ios 单击第二个文本字段时,键盘未隐藏,ios,iphone,swift,Ios,Iphone,Swift,我有两个文本字段。单击时,第一个显示qwerty键盘,第二个显示picker。 我的问题是当我点击我的第一个文本字段时,键盘正确显示。现在,在我键入任何内容后,我直接想要单击第二个文本字段,它是显示选择器,键盘应该消失,但键盘仍然存在。 我想在单击第二个文本字段时立即隐藏键盘。有两种方法可以实现此目的- 首先:使用UITextFieldDelegate。 为此— 在视图控制器的协议列表中列出UITextFieldDelegate,如下所示: @interface ViewController :

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

有两种方法可以实现此目的-

首先:使用UITextFieldDelegate。 为此— 在视图控制器的协议列表中列出UITextFieldDelegate,如下所示:

@interface ViewController : UIViewController <UITextFieldDelegate>
现在,您可以实现委托方法了。但是,为了首先实现您的目标,您需要获取UITextField实例,以了解何时输入firstTextField。因此,声明一个
UITextField
类型的属性。在接口文件中这样做-

@property(nonatomic, strong) UITextField *currentTextField;
现在,在
textfielddebeginediting
delegate方法中,在开始键入时,将firstTextField实例分配给currentTextField,如下所示-

- (void)textFieldDidBeginEditing:(UITextField *)textField{
       if(textField.tag == 1){
           self.currentTextField = textField;
       }
}
之后,在
textfielddidediting
方法中,检查您要从中出来的是不是当前的textfield,然后像这样关闭键盘-

-(void)textFieldDidEndEditing:(UITextField *)textField{
          if(textField.tag == 1){
              [self.currentTextField resignFirstResponder];
          }
          return YES;
     }
:您可以使用UIResponder。由于ViewControllers继承自UIResponder,您只需重写方法-
touchesBegind:withEvent
方法,类似于-

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

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

使用
UITextFieldDelegate
ViewDidLoad
中将delegate设置为
self
,然后放入此代码

func textFieldDidEndEditing(textField: UITextField) 
{
    yourtextfieldname.resignFirstResponder()
    return true
}
步骤1:-ViewController.h的代码:-
//在UIViewController之后添加UIExtFieldDelegate
@界面ViewController:UIViewController
步骤2:-ViewController.m的代码:-
//在viewdidLoad内部,编写以下代码,其中txtInput是输入文本字段的出口
_txtInput.delegate=self;
//最后一件事是在@end上面写下面的代码
-(BOOL)textField应返回:(UITextField*)textField
{
[textField resignFirstResponder];
返回YES;
}
//就这样用这个很简单的方法

单击第二个文本字段时,首先执行self.view.endEditing,然后执行present pickeri…但不起作用..删除文本字段并使用按钮为什么使用文本字段我正在执行相同的操作…但不起作用。您选择了哪个选项,第一个还是第二个?如果可能,发布一些代码片段。另外,使用左侧面板上的连接检查器发布故事板的屏幕截图。检查你自己,如果你已经把你的文本字段和它在故事板上的输出连接起来了。我这样做了,但它不起作用
func textFieldDidEndEditing(textField: UITextField) 
{
    yourtextfieldname.resignFirstResponder()
    return true
}
Step 1 :- Code for ViewController.h :-                                                   

//add UITextFieldDelegate just after UIViewController

@interface ViewController : UIViewController<UITextFieldDelegate>

Step 2 :- Code For ViewController.m :-

//inside viewdidLoad write following code, where txtInput is outlet for input text field

_txtInput.delegate = self;

// Last Thing write following code just above @end

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

//that's it use this very simple way