我想知道如何使键盘消失时,用户触摸以外的UITextField。
当前回答
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
其他回答
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first{
view.endEditing(true)
}
}
在我的新发展中,我以巴里为例。它工作得很好!但我不得不包括一个轻微的变化,要求解散键盘,只有文本字段被编辑。
所以,我在Barry的例子中加入了以下内容:
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
_textBeingEdited = textField;
}
-(void) textFieldDidEndEditing:(UITextField *)textField
{
_textBeingEdited = nil;
}
同时,我修改了hideKeyboard方法如下:
- (IBAction)hideKeyboard:(id)sender
{
// Just call resignFirstResponder on all UITextFields and UITextViews in this VC
// Why? Because it works and checking which one was last active gets messy.
//UITextField * tf = (UITextField *) sender;
[_textBeingEdited resignFirstResponder];
}
你需要添加一个UITapGestureRecogniser并将其分配给视图,然后在它的选择器上的UITextField上调用resign first responder。
代码:
在viewDidLoad
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
在dismissKeyboard:
-(void)dismissKeyboard
{
[aTextField resignFirstResponder];
}
(其中,aTextField是负责键盘的文本字段)
Swift 3版本是这样的
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)
对于dismissKeyboard
@objc func dismissKeyboard (_ sender: UITapGestureRecognizer) {
aTextField.resignFirstResponder()
}
在viewDidLoad 斯威夫特4.2 代码是这样的
let viewTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(dismissKeyboard))
view.addGestureRecognizer(viewTap)
@objc func dismissKeyboard() {
view.endEditing(true)
}
你可以使用UITapGestureRecongnizer方法通过点击UITextField之外的按钮来取消键盘。通过使用这个方法,每当用户在UITextField之外点击时,键盘就会被驳回。下面是使用它的代码片段。
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(dismissk)];
[self.view addGestureRecognizer:tap];
//Method
- (void) dismissk
{
[abctextfield resignFirstResponder];
[deftextfield resignFirstResponder];
}
推荐文章
- 如何使用Xcode创建。ipa文件?
- 动态改变UILabel的字体大小
- 新的自动引用计数机制是如何工作的?
- 在iPhone上确定用户是否启用了推送通知
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 错误ITMS-9000:“冗余二进制文件上传。火车1.0版本已经有一个二进制版本上传。
- Swift -转换为绝对值
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)
- 调整UITableView的大小以适应内容
- 在代码中为UIButton设置一个图像
- NSRange从Swift Range?
- UICollectionView中的单元格间距
- 我如何在我的iOS应用程序中每n分钟得到一个后台位置更新?
- 如何使用iOS创建GUID/UUID