0
0

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 1 year has passed since last update.

TextFieldがキーボードで隠れてしまう問題

Last updated at Posted at 2024-01-19

はじめに

TextFieldをタップした時にキーボードが表示されますが、その際にテキストフィールドが隠れてしまうことがありますよね?:thermometer_face:
そんな時はTextFieldを上に移動させちゃいましょう!!!
今回はcombineを使ってやってみました。
結構この実装は使うのでメモのつもりで書いてみました。

キーボードの通知を受け取って処理を行う

キーボードが表示される前と閉じる前

・指定された通知をPostされた時にその通知を受け取り、keyboardの高さを取得し、高さ分Viewを上に上げました!
・combineで書くとすごく簡単!

    private func setupKeyboardPublisher() {
        NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
            .merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification))
            .sink { [weak self] notification in
                guard let keyboardSize = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
                      let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval,
                      let self else{
                    return
                }
                switch notification.name {
                case UIResponder.keyboardWillShowNotification:
                // ここは上に上げる処理
                    alertContainerViewBottomCostraint.constant = keyboardSize.height
                case UIResponder.keyboardWillHideNotification:
                // ここは下に上げる処理
                    alertContainerViewBottomCostraint.constant = 0
                default:
                    break
                }
                UIView.animate(withDuration: duration,
                               delay: 0,
                               options: .curveEaseInOut) {
                    self.view.layoutIfNeeded()
                }
            }.store(in: &disposeBag)
    }
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?