1. Add an Observer to NotificationCenter
  2. How to get keyboard frame value with notification observer
  3. Transforming Views
  • addObserver in NotificationCenter
  • notification in handler
  • UIView.animate()
  • removeObserver

addObserver(_:selector:name:object:)

Adds an entry to the notification center’s dispatch table with an observer and a notification selector, and an optional notification name and sender.

NotificationCenter.default

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

Observer - View Life Cycle

You can just put them on viewDidLoad() at first but viewDidLoad is invoked only when the viewController is loaded. because of it is observer, it should be removed someday. So we need to addObserver in viewWillAppear and remove observer in viewWillDisappear

notification

notification.userInfo : Storage for values or objects related to this notification.

the result of print(notification.userInfo)

apr-24-1

여기서 NSRect 값인 UIKeyboardFrameEndUserInfoKey (i.e 키보드 frame)을 사용하기 위해서 다음과 같이 UIResponder 를 사용하여 접근해야한다.

guard let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }

the result of print(value) : NSRect: ((0, 477), (375, 335))

NSRect print의 ()는 원래 {}로 출력된다. 문법 문제로 인해 위와 같이 수정.

casting to cgRectValue

let keyboardFrame = value.cgRectValue

How to transform View

CGAffineTransform

An affine transformation matrix for use in drawing 2D graphics

view.transform = CGAffineTransform(translationX: 0, y: -difference - 16)

UIResponder

An abstract interface for responding to and handling events.

UIView.animate()

Whenever you want to make an animate with View just remember damping - 0.5 0 1 1 .curveEaseOut

    @objc fileprivate func handleKeyboardHide() {
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            self.view.transform = .identity
        })
    }

removeObserver

Don’t forget to remove observer to avoid retain cycle

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }

태그: ,

카테고리:

업데이트:

댓글남기기