본문 바로가기
iOS/설명

[iOS] Keyboard와 동일한 애니메이션 적용하기

by Sky Titan 2023. 1. 7.
728x90
 

Animate With The iOS Keyboard In Swift

Create smooth layout animations when the iOS keyboard shows and hides.

www.advancedswift.com

 Keyboard가 보이고 사라질 때, NSNotificationd의 userInfo에 들어있는 필드들을 통해서 keyboard의 크기와 animation duration, curve정보까지 받아낼 수 있다.

 

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var labelTopMargin: NSLayoutConstraint!
    let defaultTopMargin: CGFloat = 500
    
    override func viewDidLoad() {
        super.viewDidLoad()
        labelTopMargin.constant = defaultTopMargin
        
        // Subscribe to Keyboard Will Show notifications
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)

        // Subscribe to Keyboard Will Hide notifications
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hideKeyboard)))
    }
    
    @objc
    func hideKeyboard() {
        textField.resignFirstResponder()
    }
    
    @objc
    dynamic func keyboardWillShow(_ notification: NSNotification) {
        animateLabelWithKeyboard(notification: notification)
    }
        
    @objc
    dynamic func keyboardWillHide(_ notification: NSNotification) {
        animateLabelWithKeyboard(notification: notification)
    }
    
    func animateLabelWithKeyboard(notification: NSNotification) {
        animateWithKeyboard(notification: notification, animations: { keyboard in
            self.labelTopMargin.constant = self.defaultTopMargin - (UIScreen.main.bounds.height - keyboard.origin.y)
        })
    }
    
}
extension ViewController {
    func animateWithKeyboard(notification: NSNotification, animations: ((_ keyboardFrame: CGRect) -> Void)?) {
        // Extract the duration of the keyboard animation
        let durationKey = UIResponder.keyboardAnimationDurationUserInfoKey
        let duration = notification.userInfo![durationKey] as! Double
        
        // Extract the final frame of the keyboard
        let frameKey = UIResponder.keyboardFrameEndUserInfoKey
        let keyboardFrameValue = notification.userInfo![frameKey] as! NSValue
        
        // Extract the curve of the iOS keyboard animation
        let curveKey = UIResponder.keyboardAnimationCurveUserInfoKey
        let curveValue = notification.userInfo![curveKey] as! Int
        let curve = UIView.AnimationCurve(rawValue: curveValue)!

        // Create a property animator to manage the animation
        let animator = UIViewPropertyAnimator(
            duration: duration,
            curve: curve
        ) {
            // Perform the necessary animation layout updates
            animations?(keyboardFrameValue.cgRectValue)
            
            // Required to trigger NSLayoutConstraint changes
            // to animate
            self.view?.layoutIfNeeded()
        }
        
        // Start the animation
        animator.startAnimation()
    }
}

중앙의 label이 keyboard의 타이밍과 맞춰 함께 움직인다.

728x90

댓글