このコードをコピーするだけで実装できます。
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の経験が浅いため、間違いがあるかもしれません。
英語の記事