我一直在到处找这个,但我似乎找不到。我知道如何解雇使用Objective-C键盘,但我不知道如何使用Swift?有人知道吗?


当前回答

使用IQKeyboardmanager,将帮助您解决简单.....

/////////////////////////////////////////

[如何禁用键盘..][1].

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

   @IBOutlet weak var username: UITextField!
   @IBOutlet weak var password: UITextField!

   override func viewDidLoad() {
      super.viewDidLoad() 
      username.delegate = self
      password.delegate = self
      // Do any additional setup after loading the view, typically from a nib.
   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
   }

   func textFieldShouldReturn(textField: UITextField!) -> Bool // called when   'return' key pressed. return NO to ignore.
   {
      textField.resignFirstResponder()
      return true;
   }

   override func touchesBegan(_: Set<UITouch>, with: UIEvent?) {
     username.resignFirstResponder()
     password.resignFirstResponder()
     self.view.endEditing(true)
  }
}

其他回答

斯威夫特3:

扩展选择器作为参数,能够做额外的东西在解散函数和cancelsTouchesInView,以防止扭曲与触摸的其他元素的视图。

extension UIViewController {
    func hideKeyboardOnTap(_ selector: Selector) {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
}

用法:

override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}

func dismissKeyboard() {
    view.endEditing(true)
    // do aditional stuff
}

作为一个新手程序员,当人们给出更熟练和不必要的回答时,可能会感到困惑……你不需要做上面所示的任何复杂的事情!

这是最简单的选择……在这种情况下,你的键盘出现在响应文本字段-在你的触摸屏函数中,只需添加resignFirstResponder函数。如下所示-键盘将关闭,因为First Responder被释放(退出Responder链)…

override func touchesBegan(_: Set<UITouch>, with: UIEvent?){
    MyTextField.resignFirstResponder()
}

对于Swift 3来说,这非常简单

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

如果你想隐藏键盘按回车键

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

但在第二种情况下,你还需要通过委托从所有文本字段的ViewController在主。故事板

如果你使用滚动视图,它会简单得多。

只需在故事板中交互式地选择解散。

在Swift 4中,添加@objc:

在viewDidLoad中:

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
view.addGestureRecognizer(tap)

功能:

@objc func dismissKeyboard() {
  view.endEditing(true)
}