티스토리 뷰

키보드가 올라가고 내려갈때 같이 움직이는 뷰를 처리하는 방법입니다.

NotificationCenter

등록된 옵저버에 정보를 담은 신호를 보내는 방식

 

 

1. NotificationCenter에 옵저버를 추가해줍니다. (show, hide 2개)

NotificationCenter.default.addObserver(self, selector: #selector(adjustInputView), name: UIResponder.keyboardWillShowNotification, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(adjustInputView), name: UIResponder.keyboardWillHideNotification, object: nil)

 

2. 옵저버가 이벤트를 관찰했을 때 처리할 메서드를 작성해줍니다.

@objc private func adjustInputView(notification: Notification) {
    guard let userInfo = notification.userInfo else { return }
    guard let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
    
    if notification.name == UIResponder.keyboardWillShowNotification{
        let adjustmentHeight = -keyboardFrame.height + view.safeAreaInsets.bottom
        keyboardHeaderBottomConstraint.constant = adjustmentHeight
        
        UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)
        
        
    } else {
        keyboardHeaderBottomConstraint.constant = 0
        UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut], animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)
        
    }
}

 

댓글
공지사항