放弃触摸键盘

发布于 2025-01-03 11:14:22 字数 635 浏览 1 评论 0原文

我发现一些代码可以帮助我在用户触摸 UITextView 元素上的屏幕时退出键盘。

它看起来是这样的:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if([self.speechBubble.speechText isFirstResponder] && [touch view] != self.speechBubble.speechText){
    [self.speechBubble.speechText resignFirstResponder];
}
[super touchesBegan:touches withEvent:event];
}

到目前为止,它工作得很好,如果用户触摸文本视图之外的任何地方,就会删除键盘。但是,它仅适用于我运行它的特定对象,因此如果我有两个语音气泡,它将不起作用。

我怎样才能改变这个,以便任何语音气泡都具有相同的效果? (我可以将此代码从我的 ViewController 移动到我的 SpeechBubble 类,但我对如何使用 [触摸视图] 获取语音Bubble 视图之外的触摸有一个小问题。)谢谢

I've found some code that helps me resign the keyboard when a user touches the screen off of the UITextView element.

Here's how it looks:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if([self.speechBubble.speechText isFirstResponder] && [touch view] != self.speechBubble.speechText){
    [self.speechBubble.speechText resignFirstResponder];
}
[super touchesBegan:touches withEvent:event];
}

This works perfectly so far, and will remove the keyboard if a user touches anywhere outside of the text view. However, it only works for the particular object that I'm running it for, so if I have two speechBubbles, it won't work.

How can I change this so that ANY speechBubble will have the same effect? (I could move this code from my ViewController to my SpeechBubble class, but I'd have a little issue with how to use [touch view] to get touches outside of the speechBubble's view. ) Thanks

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

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

发布评论

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

评论(1

撩起发的微风 2025-01-10 11:14:22

我最近发现的可能对您有用的东西是:

[self.view endEditing:YES];

它将从当前拥有它的任何元素中退出第一响应者,而无需您自己手动跟踪它。

参考您的示例代码,类似的东西可能会起作用,具体取决于您的语音气泡的工作方式:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  UITouch *touch = [[event allTouches] anyObject];
  // Note the '!':
  if(![[touch view] class] isKindOfClass [speechBubble class]]){
    // It's not a bubble they touched, dismiss the keyboard:
    [self.view endEditing:YES];
  }
  [super touchesBegan:touches withEvent:event];
}

Something I just discovered recently that may be of use to you is:

[self.view endEditing:YES];

It will resign first responder from any element that currently has it without you having to manually keep track of it yourself.

In reference to your example code, something like this might work, depending on how your speechBubbles work:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  UITouch *touch = [[event allTouches] anyObject];
  // Note the '!':
  if(![[touch view] class] isKindOfClass [speechBubble class]]){
    // It's not a bubble they touched, dismiss the keyboard:
    [self.view endEditing:YES];
  }
  [super touchesBegan:touches withEvent:event];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文