如何在不按 Return 键或任何其他可控按钮的情况下关闭键盘

发布于 2024-11-28 11:11:39 字数 172 浏览 1 评论 0原文

我看过很多关于如何在按回车键或操作某些按钮时隐藏键盘的示例。

但我的情况有所不同:如何仅在文本字段外部单击即可关闭键盘?想象一下用户点击了文本字段来输入一些文本...但他后悔了,只想隐藏键盘并继续查看屏幕,就像点击文本字段之前一样

我不知道该怎么做

提前感谢

佩德罗

I have seen many samples on how to hide the keyboard when pressing return or actioning some button.

But my case is different: How do I dismiss the keyboard just clicking outside the TextField? Imagine the user has tapped a TextField to enter some text... But he regrets and just want to hide the keyboard and continue viewing the screen as before tapping in the textfield

I don't find how to do it

Thanks in advance

Pedro

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

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

发布评论

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

评论(3

愛上了 2024-12-05 11:11:39

实施touchesBegan并放弃作为第一响应者的文本字段。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [activeTextField resignFirstResponder];
}

如果您有多个文本字段,则应在 activeTextField 实例变量中存储指向当前活动文本字段的指针。为此,您必须将 self 设置为所有文本字段的委托并实现此委托方法:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    activeTextField = textField;
}

Implement touchesBegan and resign the text field as first responder.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [activeTextField resignFirstResponder];
}

If you have multiple text fields, you should store a pointer to currently active one in activeTextField instance variable. To do that, you would have to set self as delegate for all text fields and implement this delegate method:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    activeTextField = textField;
}
幸福不弃 2024-12-05 11:11:39

试试这个代码。

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent*)event 
{
 UITouch *touch = [touches anyObject];
 if([touch view] == self.view)
    [textField resignFirstResponder];
}

Try this code.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent*)event 
{
 UITouch *touch = [touches anyObject];
 if([touch view] == self.view)
    [textField resignFirstResponder];
}
撞了怀 2024-12-05 11:11:39

您可以在事件外部进行润色时对第一响应者进行签名。
否则看看这个答案
iPhone,触摸 UITextField 外部时关闭键盘

You can rasignfirstresponder on touch up outside event.
Otherwise have a look at this answer
iphone, dismiss keyboard when touching outside of UITextField

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