我想知道如何使键盘消失时,用户触摸以外的UITextField。
当前回答
藏品视图:
// the keyboard follows the dragging touch off screen, and may be pulled upward again to cancel the dismiss
collectionView.keyboardDismissMode = .interactive
// dismisses the keyboard when a drag begins
collectionView.keyboardDismissMode = .onDrag
其他回答
最好是让你的UIView成为UIControl的一个实例(在界面构建器中),然后连接他们的TouchUpInside事件来解散键盘方法。这个IBAction方法看起来像:
- (IBAction)dismissKeyboard:(id)sender {
[aTextBox resignFirstResponder];
}
斯威夫特4
用这个扩展方法设置你的UIViewController,例如在viewDidLoad中:
override func viewDidLoad() {
super.viewDidLoad()
self.setupHideKeyboardOnTap()
}
即使点击导航栏,键盘也会被取消。
import UIKit
extension UIViewController {
/// Call this once to dismiss open keyboards by tapping anywhere in the view controller
func setupHideKeyboardOnTap() {
self.view.addGestureRecognizer(self.endEditingRecognizer())
self.navigationController?.navigationBar.addGestureRecognizer(self.endEditingRecognizer())
}
/// Dismisses the keyboard from self.view
private func endEditingRecognizer() -> UIGestureRecognizer {
let tap = UITapGestureRecognizer(target: self.view, action: #selector(self.view.endEditing(_:)))
tap.cancelsTouchesInView = false
return tap
}
}
看看这个,这是最简单的方法,
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.view endEditing:YES];// this will do the trick
}
Or
这个库将处理包括滚动条自动滚动,点击空间隐藏键盘等…
https://github.com/michaeltyson/TPKeyboardAvoiding
objective - c:
在ViewController中添加这段代码。M文件:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
迅速:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
只是使用这段代码在您的.m文件,它将辞职的文本字段,当用户点击文本字段之外。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[textfield resignFirstResponder];
}
推荐文章
- 如何删除默认的导航栏空间在SwiftUI导航视图
- 如何在iOS中使用Swift编程segue
- Swift -整数转换为小时/分钟/秒
- Swift:声明一个空字典
- 在成功提交我的应用程序后,“太多符号文件”
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- 如何从UIImage (Cocoa Touch)或CGImage (Core Graphics)获取像素数据?
- 在Swift中如何调用GCD主线程上的参数方法?
- NSLayoutConstraints是可动画的吗?
- iOS -构建失败,CocoaPods无法找到头文件
- CFNetwork SSLHandshake iOS 9失败
- 请求失败:不可接受的内容类型:文本/html使用AFNetworking 2.0
- 缺少推荐的图标文件-该包不包含iPhone / iPod Touch的应用程序图标,像素为“120x120”,png格式
- 以编程方式创建segue