[ios] NotificationCenter를 이용한 키보드 높이에 따른 뷰 올리기

감자·2020년 9월 14일
1

ios

목록 보기
1/9

왜 작성하는가?

->
프로젝트를 진행하면서 값을 입력하기 위해서 키보드가 올라오면서 기존에 TextView를 가리게 되어서를 이를 해결하고 그 과정에서 얻게 된 것을 여기에 기록할려고 한다!

위와 같은 TexView가 키보드 위로 올라오게된다.

어떤 방식으로 코드를 작성하였는가?

    extension MainQuestionViewController{
    
    func registerForKeyboardNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(adjustTextFieldConstraintsToKeyboard(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)
    }
    
    @objc  private func adjustTextFieldConstraintsToKeyboard(noti:Notification){
        guard let userInfo = noti.userInfo else{
            fatalError()
        }
        
        guard let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else{
            fatalError()
        }
        if noti.name == UIResponder.keyboardWillShowNotification{
            var keyboardHeight = (keyboardFrame.height - view.safeAreaInsets.bottom)
            constraintToBottomForTag.constant = keyboardHeight
        }
        else{
            
        }        
    }
}    

위와 같이 registerForKeyboardNotification() 라는 메소드 안에 NotificationCenter에 observer를 등록하여(notification에 대한 설명은 뒤에서 할 예정이다. ) 키보드가 올라오는 것을 관찰하게 하는 로직을 작성한다. 그리고 observer에 해당되는 액션인adjustTextFieldConstraintsToKeyboard()라는 메소드를 작성한다.

  • var keyboardHeight = (keyboardFrame.height -view.safeAreaInsets.bottom)
노치 디자인이 적용된 아이폰 부터는 키도브 디자인이 개편되었다. 기존 아이폰은 
키보드에 SafeArea가 포함되지 않지만 노치 디자인의 아이폰에서 부터는
키보드에  safeArea크기 만큼이 포함되어 뵤여지는데 그래서 keyboardFrame.height에서 safeArea의 bottom을 빼주는 것이다.
(이렇게 해야 온전한 키보드이 높이를 구할 수 있다. 그렇지 않으면 키보드가 올라오기 이전에 safeArea에다 safeaArea높이를 포한 키보드 높이를 더하게 되는 것이 된다. 
그러면 키보드가 가려지는 현상을 해결 할 수 있는 있지만 키보드 끝에 기존 View에 
끝이 오지 않고 Margin이 생기게 되므로 본래 의도와 달라지게 된다.)
   override func viewWillAppear(_ animated: Bool) {
        registerForKeyboardNotification()
        self.textFieldToHeadLine.becomeFirstResponder()
    }

viewWillAppear()가 실행될 때 registerForKeyboardNotification() 메소스를 이용하여 notification에 observer를 등록하게 된다.

해결을 하면서 얻게된 것

  • NotificationCenter의 동작방식

    특정 객체가 NotificationCenter에 등록된 Event를 발생기키면 해당 Event 발생하기를 관찰하고 있는 Observer들이 Event발생에 대한 행동을 취해주는 것이 NotificationCenter의 동작 방식이다. 이때 특정한 객체가 Event를 발생해는 것을 Post라고 한다.

0개의 댓글