Table of Contents
UITextField などをタップした時に出現するキーボードの高さを取得したいという場合があります。
これは、キーボード出現時に NotificationCenter で通知を送る設定をすることで実現できます。
キーボードの高さを取得するサンプルソースコード
Swift3では以前より簡潔に書くことができます。
NotificationCenterの設定
ViewController の viewDidLoad などで、以下のように NotificationCenter の登録を行っておきます。
NotificationCenter.default.addObserver(
self,
selector: #selector(self.showKeyboard(notification:)),
name: NSNotification.Name.UIKeyboardDidShow,
object: nil
)
第3引数 name に NSNotification.Name.UIKeyboardDidShow を設定することで、キーボード出現後に通知を行うメソッドを設定できます。
キーボードの情報を受け取るメソッドを設定
キーボード出現後に、第2引数として登録した以下のメソッド showKeyboard(notification:) が呼び出されます。
func showKeyboard(notification: Notification) {
if let userInfo = notification.userInfo {
if let keyboardFrameInfo = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue {
// キーボードの高さを取得
print(keyboardFrameInfo.cgRectValue.height)
}
}
}
このとき、このメソッドの引数 notification の userInfo にキーボードに関する情報が含まれています。
print で notification を出力してみると、その中身が以下のようになっていることが確認できます。
userInfo の index に引き出したい情報に関する値を入れます。ここでは UIKeyboardFrameEndUserInfoKey を index として指定します。
例えば、iPhone5のシミュレータでは「253.0」が出力されます。


ピンバック: キーボードで入力欄が隠れないように対応[Swift4](2018/3/29追記) | Let's enjoy programming !