오늘은 키보드가 올라올 때 TextView를 가리는 현상을 해결하는 법을 알아보겠습니다.
TextView에 키보드로 입력을 할 때 키보드 때문에 글이 가려지는 현상이 있습니다.
그래서 여러 시도를 해보았습니다. (뷰 자체를 올리는 방법 등..)
그 중에 가장 깔끔히 잘되는 방법으로는 TextView의 contentInset을 변경하는 것이었습니다.
그래서 TextView의 ContentInset을 변경하는 방법으로 해결해보겠습니다.
TextView를 클릭하면 키보드가 올라 오게 되는데요.
Notification을 통해서 키보드가 올라 올 때 실행할 작업을 추가해 줄 수 있습니다.
바로 코드로 보겠습니다.
Notification을 통해서 키보드가 올라올 때, 키보드가 내려갈 때 호출할 메서드를 지정할 수 있습니다.
Notication의 name에는 아래와 같은 이름을 지정할 수 있습니다.
keyboardWillShowNotification는 이름에서 알 수 있듯이 키보드가 올라올 때의 Notification이고, keyboardWillHideNotification은 키보드가 내려갈 때의 Notificaion입니다.
UIResponder.keyboardWillShowNotification
UIResponder.keyboardWillHideNotification
override func viewDidLoad() {
setUpNotification()
}
private func setUpNotification() {
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
이제 키보드가 올라올 떄 TextView의 contentInset을 조정하도록 해보겠습니다.
먼저 키보드의 프레임을 구합니다.
그리고 textView의 contentInset의 bottom을 키보드의 높이 만큼 지정해줍니다.
그러면 textView의 bottom contentInset이 더 커져 내용이 가려지지 않게 됩니다.
그리고 키보드가 내려갈 때 contentInset을 원래의 상태로 돌려줍니다.
@objc private func keyboardWillShow(_ notification: Notification) {
guard let userInfo = notification.userInfo as NSDictionary?,
var keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
keyboardFrame = view.convert(keyboardFrame, from: nil)
var contentInset = textView.contentInset
contentInset.bottom = keyboardFrame.size.height
textView.contentInset = contentInset
textView.scrollIndicatorInsets = textView.contentInset
}
그리고 키보드가 내려갈 때 contentInset을 원래의 상태로 돌려줍니다.
@objc private func keyboardWillHide(_ notification: Notification) {
textView.contentInset = UIEdgeInsets.zero
textView.scrollIndicatorInsets = textView.contentInset
}
감사합니다.