从另一个视图 ios 导航时,键盘不会关闭

Saa*_*aad 2 objective-c ios resignfirstresponder

我有两个视图控制器。假设,viewcontroller1viewcontroller2

viewcontroller1我有一个文本视图和一个按钮。当我单击 textview 键盘打开时,如果按下按钮键盘很好地关闭。我正在使用此代码来关闭键盘。

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)
                                               to:nil
                                             from:nil
                                         forEvent:nil];
Run Code Online (Sandbox Code Playgroud)

但是,当键盘打开时,我转到viewcontroller2然后返回viewcontroller1,在 viewWillAppear 方法中,我使用相同的代码来关闭键盘,但不会关闭键盘。看到这一点,我感到非常惊讶。请帮忙

NSN*_*oob 5

摆脱那个发送动作例程

首先,删除这一行:

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder)
                                               to:nil
                                             from:nil
                                         forEvent:nil];
Run Code Online (Sandbox Code Playgroud)

选项 1

现在在你的另一个 ViewController 的 viewDidLoad 中,写下这一行:

[self.view endEditing:YES];
Run Code Online (Sandbox Code Playgroud)

选项 2

您还可以在导航到第二个 VC 之前退出 textField 和 textViews。例如在你的第一个 VC 的导航代码中这样做:

//Method moveToSecondVC()
[self.view endEditing:YES];
[self.navigationController pushViewController:secondVC animated:YES];
Run Code Online (Sandbox Code Playgroud)

选项 3

如果您使用的是 segue,则可以在 prepareForSegue 方法中进行,例如:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [self.view endEditing:YES];
}
Run Code Online (Sandbox Code Playgroud)

选项 4

或者,您可以在viewWillDisappearViewControllers 的方法中编写这一行,例如:

- (void)viewWillDisappear:(BOOL)animated 
{
    [self.view endEditing:YES];

    [super viewWillDisappear:animated];
}  
Run Code Online (Sandbox Code Playgroud)