0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TextField外をタップしたときにキーボードを閉じる

Posted at

入力項目がある画面はだいたいタップでキーボードを閉じたい時の対応
※これもよくあるTipsなのでメモ程度として

画面をタップされた時に処理を行う

なにはともあれ、画面をタップされた時に閉じる処理を呼びたいということで、
ViewControllerを拡張しておきます。
以下コード

extension UIViewController {
    func setHideKeyboardTapped() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.hideKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

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

上記で拡張できたので、対象のViewControllerで setHideKeyboardTappedをviewDidLoadあたりで呼び出しておけばOK。

参考

【iOS】UITextField のキーボードを閉じる処理について

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?