Swift
keyboard height 구하는 방법
진태우
2018. 4. 3. 19:53
키보드에 다른 화면을 구성하고 싶을 때 키보드의 높이와 다르게 배치하면 이쁘지 않은 화면이 될 수 있다. 이럴 경우, 아이폰의 종류에 따라 딱 맞는 키보드의 높이를 가져와 사용하면 유용할 것이다.
아래는 키보드가 보일 경우와 숨겨질 경우, 호출되는 notification을 observer로 받아서 키보드의 높이를 구하는 코드이다.
키보드의 높이를 구하는 것 뿐만아니라 다른 로직도 구현할 수 있다.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// keyboardWillShow, keyboardWillHide observer 등록
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//
func keyboardWillShow(_ notification:NSNotification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
print("keyboardHeight = \(keyboardHeight)")
}
// 원하는 로직...
}
func keyboardWillHide(_ notification:NSNotification) {
// 원하는 로직...
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// observer를 전부 제거
NotificationCenter.default.removeObserver(self)
}
위 코드에는 두가지만 observer로 받아서 사용했지만 그 외에도 UIKeyboardDidShow, UIKeyboardDidHide가 더 있었다.
호출 시점에 따라 원하는 notification을 사용하면 될 것 같다.
UIKeyboardWillShow : 키보드가 보이기 전에 호출.
UIKeyboardDidShow : 키보드가 보인 후에 호출.
UIKeyboardWilllHide : 키보드가 숨겨지기 전에 호출.
UIKeyboardDidHide : 키보드가 숨겨진 후에 호출.