如何关闭 iOS 键盘?

发布于 2024-11-27 16:11:52 字数 53 浏览 2 评论 0原文

我有一个 UITextfield,我想关闭键盘。无论我使用什么代码,我似乎都无法让键盘消失。

I have a UITextfield that i'd like to dismiss the keyboard for. I can't seem to make the keyboard go away no matter what code i use.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

小草泠泠 2024-12-04 16:11:52

如果您有多个文本字段并且不知道哪个是第一响应者(或者您根本无法从编写此代码的任何位置访问文本字段),您可以调用 endEditing:包含文本字段的父视图。

在视图控制器的方法中,它看起来像这样:

[self.view endEditing:YES];

该参数强制文本字段放弃第一响应者状态。如果您使用委托来执行验证并希望停止所有操作,直到文本字段的内容有效,您也可以像这样编写代码:

BOOL didEndEditing = [self.view endEditing:NO];
if (didEndEditing) {
    // on to the next thing...
} else {
    // text field must have said to first responder status: "never wanna give you up, never wanna let you down"
}

endEditing: 方法比告诉各个文本字段要好得多resignFirstResponder,但由于某种原因我直到最近才发现它。

If you have multiple text fields and don't know which one is first responder (or you simply don't have access to the text fields from wherever you are writing this code) you can call endEditing: on the parent view containing the text fields.

In a view controller's method, it would look like this:

[self.view endEditing:YES];

The parameter forces the text field to resign first responder status. If you were using a delegate to perform validation and wanted to stop everything until the text field's contents were valid, you could also code it like this:

BOOL didEndEditing = [self.view endEditing:NO];
if (didEndEditing) {
    // on to the next thing...
} else {
    // text field must have said to first responder status: "never wanna give you up, never wanna let you down"
}

The endEditing: method is much better than telling individual text fields to resignFirstResponder, but for some reason I never even found out about it until recently.

故人爱我别走 2024-12-04 16:11:52
[myTextField resignFirstResponder]

此处,显示和隐藏键盘部分中的第二段。

[myTextField resignFirstResponder]

Here, second paragraph in the Showing and Hiding the Keyboard section.

ゞ花落谁相伴 2024-12-04 16:11:52

我发现 endEditingresignFirstResponder 失败的情况。在这些情况下,这对我有用。

对象

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];    
[self setEditing:NO];

Swift

UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)

I've discovered a case where endEditing and resignFirstResponder fail. This has worked for me in those cases.

ObjC

[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];    
[self setEditing:NO];

Swift

UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
深海夜未眠 2024-12-04 16:11:52

在某些情况下,没有文本字段是第一响应者,但键盘在屏幕上。
在这些情况下,上述方法无法关闭键盘。

如何实现这一点的一个示例:

  1. 以编程方式将 ABPersonViewController 推送到屏幕上;打开任何联系人;
  2. 触摸“注释”字段(成为第一响应者并启动键盘);
  3. 在任何其他字段上向左滑动即可显示“删除”按钮;
  4. 此时,文本字段中没有第一响应者(只需以编程方式检查),但键盘仍然存在。调用 [view endEditing:YES] 不会执行任何操作。

在这种情况下,您还需要要求视图控制器退出编辑模式:

[viewController setEditing:NO animated:YES];

There are cases where no text field is the first responder but the keyboard is on screen.
In these cases, the above methods fail to dismiss the keyboard.

One example of how to get there:

  1. push the ABPersonViewController on screen programmatically; open any contact;
  2. touch the "note" field (which becomes first responder and fires up the keyboard);
  3. swipe left on any other field to make the "delete" button appear;
  4. by this point you have no first responder among the text fields (just check programmatically) but the keyboard is still there. Calling [view endEditing:YES] does nothing.

In this case you also need to ask the view controller to exit the editing mode:

[viewController setEditing:NO animated:YES];
巴黎盛开的樱花 2024-12-04 16:11:52

我建议您在头文件上添加操作:

-(IBAction)removeKeyboard;

在实现中,编写如下内容:

-(IBAction)removeKeyboard
{
[self.textfield resignFirstResponder];
}

在 NIB 文件中,通过选项 DidEndOnExit 从 UITextFiled 连接到文件所有者。这样,当你按回车键时,键盘就会消失。

希望有帮助!

I suggest you add and action on your header file:

-(IBAction)removeKeyboard;

And in the implementation, write something like this:

-(IBAction)removeKeyboard
{
[self.textfield resignFirstResponder];
}

In the NIB file, connect from the UITextFiled to the File's Owner on the option DidEndOnExit. That way, when you press return, the keyboard will disappear.

Hope it helps!

御弟哥哥 2024-12-04 16:11:52

在视图控制器 YourViewController.h 文件中,确保实现 UITextFieldDelegate 协议:

@interface YourViewController : <UITextFieldDelegate>

@end

然后,在 YourViewController.m 文件中,实现以下实例方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.yourTextField1 resignFirstResponder];
    [self.yourTextField2 resignFirstResponder];
    ...
    [self.yourTextFieldn resignFirstResponder];
}

In your view controller YourViewController.h file, make sure you implement UITextFieldDelegate protocol :

@interface YourViewController : <UITextFieldDelegate>

@end

Then, in YourViewController.m file, implement the following instance method:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.yourTextField1 resignFirstResponder];
    [self.yourTextField2 resignFirstResponder];
    ...
    [self.yourTextFieldn resignFirstResponder];
}
沙与沫 2024-12-04 16:11:52

放弃应用程序中的任何文本字段

UIApplication.shared.keyWindow?.endEditing(true)

这种方法很干净并且可以保证工作,因为根据定义,keyWindow 是显示键盘的所有可能视图的根视图(来源):

按键窗口接收键盘和其他非触摸相关事件。一次只有一个窗口可能是关键窗口。

To resign any text field in the app

UIApplication.shared.keyWindow?.endEditing(true)

This approach is clean and guarantied to work because the keyWindow is, by definition, the root view of all possible views displaying a keyboard (source):

The key window receives keyboard and other non-touch related events. Only one window at a time may be the key window.

殤城〤 2024-12-04 16:11:52

这将放弃一个特定的文本字段

// Swift
TextField.resignFirstResponder()

// Objective C
[TextField resignFirstResponder];

要放弃任何文本字段,请使用以下代码

// Swift
self.view!.endEditing(true)

// Objective C
[self.view endEditing:YES];

This will resign one particular text field

// Swift
TextField.resignFirstResponder()

// Objective C
[TextField resignFirstResponder];

To resign any text field use below code

// Swift
self.view!.endEditing(true)

// Objective C
[self.view endEditing:YES];
痞味浪人 2024-12-04 16:11:52

作为最后的手段

as a last resort ????

let dummyTextView = UITextView(frame: .zero)
view.addSubview(dummyTextView)
dummyTextView.becomeFirstResponder()
dummyTextView.resignFirstResponder()
dummyTextView.removeFromSuperview()
成熟稳重的好男人 2024-12-04 16:11:52

如果您不知道哪个文本字段是第一响应者,您可以找到它。我使用这个函数:

UIView *resignFirstResponder(UIView *theView)
{
    if([theView isFirstResponder])
    {
        [theView resignFirstResponder];
        return theView;
    }
    for(UIView *subview in theView.subviews)
    {
        UIView *result = resignFirstResponder(subview);
        if(result) return result;
    }
    return nil;
}

然后在你的代码中调用:

    UIView *resigned = resignFirstResponder([UIScreen mainScreen]);

If you don't know which textField is the first responder you can find it. I use this function:

UIView *resignFirstResponder(UIView *theView)
{
    if([theView isFirstResponder])
    {
        [theView resignFirstResponder];
        return theView;
    }
    for(UIView *subview in theView.subviews)
    {
        UIView *result = resignFirstResponder(subview);
        if(result) return result;
    }
    return nil;
}

Then in your code call:

    UIView *resigned = resignFirstResponder([UIScreen mainScreen]);
萌︼了一个春 2024-12-04 16:11:52

您只需将 yourTextFieldName 替换为,您猜对了!你的文本字段。这将关闭键盘。

[yourTextFieldName resignFirstResponder];

You just replace yourTextFieldName with, you guessed it! your textfield. This will close the keyboard.

[yourTextFieldName resignFirstResponder];
灰色世界里的红玫瑰 2024-12-04 16:11:52
-(void)methodName
{
    [textFieldName resignFirstResponder];
}

使用 didEndOnExit 调用此方法 (methodName)

-(void)methodName
{
    [textFieldName resignFirstResponder];
}

call this method (methodName) with didEndOnExit

_畞蕅 2024-12-04 16:11:52

对于Swift 3

你可以像这样隐藏键盘:

textField.resignFirstResponder()

如果你想在用户按下“intro”按钮时隐藏键盘,你必须实现以下UITextFieldDelegate方法:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true
}

For Swift 3

You can hide the keyboard like this:

textField.resignFirstResponder()

If you want to hide the keyboard when the user press the "intro" button, you have to implement the following UITextFieldDelegate method:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true
}
淡忘如思 2024-12-04 16:11:52
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    // your code

    [textField reloadInputViews];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    // your code

    [textField reloadInputViews];
}
哀由 2024-12-04 16:11:52

3简单&快速步骤

UITextFieldDelegate 添加到您的类中,如下所示:

class RegisterVC: UIViewController, UITextFieldDelegate {
    //class implementation 
}

在类实现中,添加委托函数 textFieldShouldEndEditing:

internal func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    self.view.endEditing(true)
    return true
}

最后一步,设置您的 UITextField 在适当的地方委托给自己。例如,在 viewDidLoad 函数中:

override func viewDidLoad(){
    super.viewDidLoad()
    myTextField1.delegate = self
    myTextField2.delegate = self
    ..
    ..
}

现在,每当用户按下返回键时,键盘就会消失。

我也准备了一个示例片段,您可以从此处查看它< /a>.

3 Simple & Swift steps

Add UITextFieldDelegate to your class as below:

class RegisterVC: UIViewController, UITextFieldDelegate {
    //class implementation 
}

in class implementation, add the delegate function textFieldShouldEndEditing::

internal func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    self.view.endEditing(true)
    return true
}

and as a last step, set your UITextField(s) delegate(s) to self, in somewhere appropriate. For example, inside the viewDidLoad function:

override func viewDidLoad(){
    super.viewDidLoad()
    myTextField1.delegate = self
    myTextField2.delegate = self
    ..
    ..
}

Now, whenever user hits the return key, keyboard will dismiss.

I prepared an example snippet too, you can check it from here.

春风十里 2024-12-04 16:11:52
  1. 在 Xcode 中设置“退出时结束”事件(右键单击文本字段)。

    屏幕截图

  2. 实现该方法:

    -(IBAction) closeKeyboard:(id) 发送者 {
        [_txtField resignFirstResponder];
    }
    
  1. Set up the "Did End On Exit" event in Xcode (right click on your text field).

    Screenshot

  2. Realize this method:

    -(IBAction) closeKeyboard:(id) sender {
        [_txtField resignFirstResponder];
    }
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文