【Swift】キーボードの表示/非表示を検知する方法!UIResponder

【Swift】キーボードの表示/非表示を検知する方法!UIResponder

この記事からわかること

  • Swiftキーボード表示/非表示になったことを検知する方法
  • UIResponderkeyboardWillShowNotification/keyboardWillHideNotification使い方
  • キーボードのサイズ(横幅高さ)を取得する方法

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

環境

キーボードの表示/非表示を検知する方法

公式リファレンス:UIResponder.keyboardWillShowNotification

Swiftでキーボードが表示されたかどうかを検知するにはNotificationCenterクラスを使用してUIResponderkeyboardWillShowNotification/keyboardWillHideNotificationを観測対象にします。

keyboardWillShowNotificationではキーボードが表示されたことkeyboardWillHideNotificationではキーボードが非表示になったことを検知することができます。

NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
    .sink { [weak self] _ in
        print("キーボードが表示されたよ")
    }
    .store(in: &cancellables)

NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)
    .sink { [weak self] _ in
        print("キーボードが非表示になったよ")
    }
    .store(in: &cancellables)

Swift UIで使用できる管理クラスを実装してみました。

import SwiftUI
import Combine

final class KeyboardResponder: ObservableObject {
    @Published  var isKeyboardVisible: Bool = false
    private var cancellables = Set<AnyCancellable>()

    init() {
        NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
            .sink { [weak self] _ in
                self?.isKeyboardVisible = true
            }
            .store(in: &cancellables)

        NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)
            .sink { [weak self] _ in
                self?.isKeyboardVisible = false
            }
            .store(in: &cancellables)
    }
}

表示されたキーボードの高さを取得する

表示されたキーボードのサイズ(横幅や高さ)や座標などを取得したい場合は発行されたNSNotificationuserInfoプロパティにある辞書型の中からUIResponder.keyboardFrameEndUserInfoKeyキーで取得することが可能です。

NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
    .sink { [weak self] notification in
        print("キーボードが表示されたよ")
        guard let userInfo = notification.userInfo,
                let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
            return
        }
        print("keyboardFrame", keyboardFrame) // keyboardFrame NSRect: {{0, 610}, {440, 346}}
        print("keyboardFrame.cgRectValue", keyboardFrame.cgRectValue) // keyboardFrame.cgRectValue (0.0, 610.0, 440.0, 346.0)
        print("キーボード横幅", keyboardFrame.cgRectValue.width) // キーボード横幅 440.0
        print("キーボード高さ", keyboardFrame.cgRectValue.height) // キーボード高さ 346.0
    }
    .store(in: &cancellables)

まだまだ勉強中ですので間違っている点や至らぬ点がありましたら教えていただけると助かります。

ご覧いただきありがとうございました。

searchbox

スポンサー

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑
今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index