UIKit App 按空白處收鍵盤的方法

開發 iOS App 時,為了更好的使用者體驗,我們時常加入點選空白處收鍵盤的功能。接下來我們將針對以下兩種情況介紹按空白處收鍵盤的方法。

  • 一般的畫面,非點選 table & collection view。
  • table & collection view 點選收鍵盤的方法。

一般的畫面,非點選 table & collection view

  • 方法 1: touchesEnded 裡呼叫 endEditing

點選空白處時會觸發 controller 的 touchesEnded,因此我們在 touchesEnded 裡呼叫 endEditing 收鍵盤。

class ViewController: UIViewController {

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

結果

點選空白處可收鍵盤。

  • 方法 2: 利用 UITapGestureRecognizer,從 Interface Builder 加入

加入 UITapGestureRecognizer,讓 View 的 gestureRecognizers 連到 Tap Gesture Recognizer。

連結 UITapGestureRecognizer 的 IBAction,呼叫 endEditing 收鍵盤。

@IBAction func closeKeyboard(_ sender: Any) {
view.endEditing(true)
}
  • 方法 3: 利用 UITapGestureRecognizer,從程式加入

從程式生成 UITapGestureRecognizer,加到 controller 的 view 上。

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(closeKeyboard))
view.addGestureRecognizer(tapGestureRecognizer)
}

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

}

table & collection view 點選收鍵盤的方法

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com