LoginSignup
5
8

More than 3 years have passed since last update.

【Swift5】UIScrollView使用時にキーボード外タップでキーボードを閉じる

Last updated at Posted at 2019-05-01

UIScrollViewを使用していたところ、touchesBeganが呼ばれませんでした。
その時の備忘録です。

環境

  • Swift5
  • xcode10.2

対策

UIScrollViewを拡張する。以下のコードを追加。

extension UIScrollView {
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.next?.touchesBegan(touches, with: event)
    }
}

touchesBeganを呼ぶことができるようになりました。


    /// キーボードが出ている状態の時にキーボード外をタップしたらキーボードを閉じる
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("キーボード外をタップ")
        //キーボードを閉じる
        self.view.endEditing(true)
    }

参考

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