6
5

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 5 years have passed since last update.

【Swift】firstResponderを取得する

6
Posted at

1.はじめに

 ビュー上にUITextFieldUITextView が複数ある場合に、キーボードを閉じるためにfirstResponder を取得します。
一つづつ全てアウトレット接続したりするのは面倒なので、汎用的に使えるメソッドにまとめました。

2.コード

func getFirstResponder(view: UIView) -> UIView? {
    if view.isFirstResponder {
        return view
    }
    for subview in view.subviews {
        if let _ = getFirstResponder(view: subview) {
            return subview
        }
    }
    return nil
}

3.ポイント

 メソッド内でgetFirstResponder() を再帰的に呼んで、firstResponder を探します。
 firstResponder がないと、最終的にnil が返ってきます。

4.使い方

 表示されているキーボードを閉じるコードです。

getFirstResponder(view: view)?.resignFirstResponder()
6
5
3

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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?