如何在 iPhone 中以编程方式隐藏键盘

发布于 2024-08-27 17:08:44 字数 29 浏览 6 评论 0原文

如何在 iPhone 中以编程方式隐藏键盘?

How to hide the keyboard programmatically in iphone?

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

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

发布评论

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

评论(6

寂寞笑我太脆弱 2024-09-03 17:08:44

告诉当前第一响应者的 UIResponder 子类放弃其第一响应者状态:

[responder resignFirstResponder];

Tell the UIResponder subclass that is currently first responder to resign its first responder status:

[responder resignFirstResponder];
我不是你的备胎 2024-09-03 17:08:44
[textFieldName resignFirstResponder];
[textFieldName resignFirstResponder];
玩套路吗 2024-09-03 17:08:44

很简单:

ObjC

[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

Swift

UIApplication.shared.keyWindow?.endEditing(true)

查看 endEditing 的 UIView 类参考
导致视图(或其嵌入文本字段之一)放弃第一响应者状态。而 keyWindow 是唯一接收键盘事件的窗口,所以这个解决方案保证始终有效。

It's easy:

ObjC

[[[UIApplication sharedApplication] keyWindow] endEditing:YES];

Swift

UIApplication.shared.keyWindow?.endEditing(true)

take a look at UIView Class Reference for endEditing.
Causes the view (or one of its embedded text fields) to resign the first responder status. And keyWindow is the only window that receives keyboard events, so this solution is guarantied to always work.

删除会话 2024-09-03 17:08:44

在你的 ViewController 中调用它

[self.view endEditing:YES];

Call this in your ViewController

[self.view endEditing:YES];
静若繁花 2024-09-03 17:08:44

如果您使用 textview 那么

- (BOOL)textView:(UITextView *)textView
 shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
  if ([text isEqualToString:@"\n"])
 {
    [textView resignFirstResponder];
    [self keyboardWillHide];
 }
}

,如果您使用 textfield 那么

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
 {

[textField resignFirstResponder];

 }

If you are using textview then

- (BOOL)textView:(UITextView *)textView
 shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
  if ([text isEqualToString:@"\n"])
 {
    [textView resignFirstResponder];
    [self keyboardWillHide];
 }
}

and if you are using textfield then

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
 {

[textField resignFirstResponder];

 }
逆流 2024-09-03 17:08:44

这是快速版本:

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)

Here is the swift version:

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文