我想知道如何使键盘消失时,用户触摸以外的UITextField。
当前回答
在我的新发展中,我以巴里为例。它工作得很好!但我不得不包括一个轻微的变化,要求解散键盘,只有文本字段被编辑。
所以,我在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];
}
其他回答
在这种情况下,可以使用ScrollView,并添加到文本字段在ScrollView和我想点击ScrollView和视图,然后解散键盘。为了以防万一,我尝试创建了示例代码。像这样,
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tap(_:)))
view.addGestureRecognizer(tapGesture)
// Do any additional setup after loading the view, typically from a nib.
}
func tap(gesture: UITapGestureRecognizer) {
textField.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
你的故事板看,就像。
如果我得到你的权利,你想辞职键盘狡猾敲在文本字段之外,但你没有你的文本字段的引用。
试试这个;
Take global textField, lets call it reftextField Now in textFieldDidBeginEditing set referenced text field to - (void) textFieldDidBeginEditing:(UITextField *)textField{ reftextField = textField; } Now you can happily use on any button clock, (adding a transparent button on begin editing recomended) - (void)dismissKeyboard { [reftextField resignFirstResponder]; } Or for resigning done button try this. //for resigning on done button - (BOOL) textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES; }
在viewDidLoad 斯威夫特4.2 代码是这样的
let viewTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(dismissKeyboard))
view.addGestureRecognizer(viewTap)
@objc func dismissKeyboard() {
view.endEditing(true)
}
如果视图被嵌入到UIScrollView中,那么你可以使用以下方法:
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
前者会在表格视图滚动时将键盘动画化,后者会像股票消息应用程序一样隐藏键盘。
注意,这些都可以在iOS 7.0或更高版本上使用。
发送消息resignFirstResponder的文本文件,把它放在那里。请参阅这篇文章了解更多信息。
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务