我想知道如何使键盘消失时,用户触摸以外的UITextField。
当前回答
我拼凑了几个答案。
使用一个在viewDidLoad期间初始化的ivar:
UIGestureRecognizer *tapper;
- (void)viewDidLoad
{
[super viewDidLoad];
tapper = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(handleSingleTap:)];
tapper.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapper];
}
删除当前正在编辑的内容:
- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
[self.view endEditing:YES];
}
其他回答
我发现有些人在使用UITapGestureRecognizer方法时遇到了问题。我在保持现有按钮点击行为不变的情况下完成这一功能的最简单方法是只添加一行到@Jensen2k的答案:
[tap setCancelsTouchesInView:NO];
这使得我现有的按钮仍然可以工作,而不需要使用@Dmitry Sitnikov的方法。
在这里阅读有关属性(搜索CancelsTouchesInView): UIGestureRecognizer类引用
我不确定它将如何与滚动条一起工作,因为我看到有些人有问题,但希望其他人可能会遇到与我相同的情况。
设置文本字段委托视图didload: 重载函数viewDidLoad() { super.viewDidLoad () self. usertext .delegate = self } 添加此函数: func textFieldShouldReturn(userText: UITextField! { userText.resignFirstResponder () 返回true; }
你可以为UiView创建类别并重写touchesBegan方法,如下所示。
这对我来说很好。这是一种集中解决这一问题的方法。
#import "UIView+Keyboard.h"
@implementation UIView(Keyboard)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.window endEditing:true];
[super touchesBegan:touches withEvent:event];
}
@end
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first{
view.endEditing(true)
}
}
所以我只需要解决这个问题,之前的答案都不适用。我的情况是:一个UISearchBar,加上屏幕上的一些其他控件。我想在搜索栏之外点击键盘,但不传播到任何其他控件。当键盘被隐藏时,我希望所有的控制都能工作。
我做了什么:
1)在我的视图控制器中实现一个自定义触摸处理程序。
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if searchBar.isFirstResponder()
{
// This causes the first responder, whoever it is, to resign first responder, and hide the keyboard.
// We also "eat" the touch here and not allow it to propagate further.
view.endEditing(true)
}
else
{
// OK to propagate the touch
super.touchesBegan(touches, withEvent: event)
}
}
2)添加了一对委托方法(我的是UISearchBar,但也有类似的UITextField)。下面代码中的controlContainerView是一个UIView,里面有一堆按钮。记住,在父视图上设置userInteractionEnabled会禁用它的所有子视图。
func searchBarTextDidBeginEditing(searchBar: UISearchBar)
{
controlContainerView.userInteractionEnabled = false
someButton.userInteractionEnabled = false
}
func searchBarTextDidEndEditing(searchBar: UISearchBar)
{
searchBar.resignFirstResponder()
// Done editing: enable the other controls again.
controlContainerView.userInteractionEnabled = false
someButton.userInteractionEnabled = false
}
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务