LoginSignup
1
5

More than 5 years have passed since last update.

【Swift3】TextField以外をタップしたら、キーボードを閉じる方法

Posted at

【Swift3】TextField以外をタップしたら、キーボードを閉じる方法

TextFieldの入力後などにキーボードを閉じたい場合。
今回は入力したTextField以外をタップしたタイミングで
キーボードを閉じる処理を追加しようとしたのですが、
Swift3での書き方がわからなくて困ったので、メモです。

対処方法

まずこれを追加

import Foundation
import UIKit

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

こちらも追加

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

(Xcode9.1使用)

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