LoginSignup
0
1

More than 3 years have passed since last update.

TextViewの編集箇所がキーボードで隠れないようにする

Posted at

このコードをコピーするだけで実装できます。

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let notificationCenter = NotificationCenter.default
            notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
            notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}

@objc func adjustForKeyboard(notification: Notification) {
        guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
        let keyboardScreenEndFrame = keyboardValue.cgRectValue
        let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)

        if notification.name == UIResponder.keyboardWillHideNotification {
            textView.contentInset = .zero
        } else {
            //textViewの下にキーボードの高さ分の余白を作る
            textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height - view.safeAreaInsets.bottom, right: 0)
        }
        //スクロールインジゲーターが表示される長さ
        textView.scrollIndicatorInsets = textView.contentInset
        //編集箇所の高さ
        let selectedRange = textView.selectedRange
        //編集箇所が見えるようにする
        textView.scrollRangeToVisible(selectedRange)
    }

コメントで説明を書いていますが、Swiftの経験が浅いため、間違いがあるかもしれません。
英語の記事

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