我一直在到处找这个,但我似乎找不到。我知道如何解雇使用Objective-C键盘,但我不知道如何使用Swift?有人知道吗?
当前回答
我找到了一个简单的解决办法: 1. 添加UITapGestureRecognizer到你的视图控制器 2. 添加IBAction到你的UITapGestureRecognizer 3.最后,您可以放弃第一个响应器
class ViewController: UIViewController
{
@IBOutlet var tap: UITapGestureRecognizer!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func dismissUsingGesture(_ sender: UITapGestureRecognizer)
{
self.textField.resignFirstResponder()
label.text = textField.text!
}
}
其他回答
你可以使用swift
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
view.endEditing(true)
}
作为一个新手程序员,当人们给出更熟练和不必要的回答时,可能会感到困惑……你不需要做上面所示的任何复杂的事情!
这是最简单的选择……在这种情况下,你的键盘出现在响应文本字段-在你的触摸屏函数中,只需添加resignFirstResponder函数。如下所示-键盘将关闭,因为First Responder被释放(退出Responder链)…
override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
MyTextField.resignFirstResponder()
}
我没有看到它被提到过,但是NotificationCenter可以告诉你键盘何时打开和关闭。例如,如果你想改变cancelsTouchesInView或一起删除手势识别器,这可以被使用。
例子:
var dismissKeyboardGestureRecognizer = UITapGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
//Setup dismiss keyboard gesture
self.dismissKeyboardGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
//Add Notifications
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name:UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name:UIResponder.keyboardDidHideNotification, object: nil)
}
@objc func keyboardDidShow() {
dismissKeyboardGestureRecognizer.cancelsTouchesInView = true
view.addGestureRecognizer(dismissKeyboardGestureRecognizer)
}
@objc func keyboardDidHide() {
dismissKeyboardGestureRecognizer.cancelsTouchesInView = false
view.removeGestureRecognizer(dismissKeyboardGestureRecognizer)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
viewDidLoad()方法中只有一行代码:
view.addGestureRecognizer(UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing(_:))))
斯威夫特3
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
推荐文章
- Objective-C中方法混合的危险是什么?
- 如何使用接口生成器创建的nib文件加载UIView
- iOS如何设置应用程序图标和启动图像
- 更改UITextField和UITextView光标/插入符颜色
- 如何使用@Binding变量实现自定义初始化
- 'Project Name'是通过优化编译的——步进可能会表现得很奇怪;变量可能不可用
- Swift设置为Array
- 如何设置回退按钮文本在Swift
- 我如何能在Swift扩展类型化数组?
- Swift类错误:属性未在super处初始化。init调用
- 模拟器慢动作动画现在打开了吗?
- 如何为TableView创建NSIndexPath
- 滑动删除和“更多”按钮(就像iOS 7的邮件应用程序)
- 使UINavigationBar透明
- 如何改变推和弹出动画在一个基于导航的应用程序