프로그래밍/iOS,macOS

[iOS] 키보드를 따라 올라오는 뷰

chance 2020. 4. 8. 11:13


해당 뷰의 bottom contraint 를 키보드 사이즈에 맞춰 변경(auto layout 을 사용하지 않는 경우 해당 뷰 프레임을 직접 변경) 

@IBOutlet weak var editView: NSLayoutConstraint!

 

키보드 이벤트 등록

NotificationCenter.default.addObserver(
    self, 
    selector: #selector(MyViewController.keyboardWillShow),
    name: UIResponder.keyboardWillShowNotification,
    object: nil)
    
NotificationCenter.default.addObserver(
    self,
    selector: #selector(MyViewController.keyboardWillHide),
    name: UIResponder.keyboardWillHideNotification,
    object: nil)

 

이벤트 발생시 constraint 조정

@objc func keyboardWillShow(notification: NSNotification) {
    keyboardShowHide(notification: notification)
}

@objc func keyboardWillHide(notification: NSNotification) {
    keyboardShowHide(notification: notification)
}

func keyboardShowHide(notification: NSNotification) {
    let userInfo = notification.userInfo!
    let animationDuration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    let keyboardEndFrame = self.view.convert(keyboardFrame, from: swlf.view.window)
    let rawAnimationCurve = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber).uintValue << 16
    
    
    // ios 11 이상 safe area
    let safeArea = self.view.safeAreaLayoutGuide.layoutFrame.insetBy(dx: 0, dy: -additionalSafeAreaInsets.bottom)
    let intersection = safeArea.instersection(keyboardEndFrame)
    let height = intersection.height
    
    
    UIView.animate(
        withDuration: animationDuration, 
        delay: 0.0,
        options: UIView.AnimationOptions(rawValue: UIView.AnimationOptions.beginFromCurrentState.rawValue|rawAnimationCurve),
        animation: {
            self.editViewBottom.constant = height
            self.view.layoutIfNeeded()
        }, completion: nil)
        
}

 

엔터키 입력시 키보드 닫기

extention MyViewController: UITextFieldDelegate {
    func texFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.myTextField.resignFirstResponder()
        // or self.myTextField.endEditing(true)
        // or self.view.endEditing(true)
        return true
    }
}

 

배경 터치시 키보드 닫기

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}