초림이의 연구실

[Swift] iOS 키보드 스크롤 자동 조절

P.S.

제가 작성한 내용도 괜찮지만 유지보수 측면에서 프로덕션 환경이라면 IQKeyboardManager 라이브러리 사용을 권장드립니다 🙂

protocol KeyboardEvader where Self: UIViewController {
   var keyboardScrollView: UIScrollView { get }
   func registerForKeyboardNotification()
 }
 extension KeyboardEvader where Self: UIViewController {
   func registerForKeyboardNotification() {
     NotificationCenter.default.addObserver(
       forName: UIResponder.keyboardWillShowNotification,
       object: nil,
       queue: OperationQueue.main
     ) { [weak self] notification in
       self?.keyboardWillShow(notification: notification)
     }
     NotificationCenter.default.addObserver(
       forName: UIResponder.keyboardWillHideNotification,
       object: nil,
       queue: OperationQueue.main
     ) { [weak self] notification in
       self?.keyboardWillHide(notification: notification)
     }
   }
 private func keyboardWillShow(notification: Notification) {
     guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
       assertionFailure("Couldn't get keyboard frame.")
       return
     }
     let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height, right: 0)
     keyboardScrollView.contentInset = insets
     keyboardScrollView.scrollIndicatorInsets = insets
   }
 private func keyboardWillHide(notification: Notification) {
     keyboardScrollView.contentInset = .zero
     keyboardScrollView.scrollIndicatorInsets = .zero
   }
 }

해당 코드를 KeyboardEvader.swift로 생성. 그 후 ViewController에서 상속받도록하고 registerForKeyboardNotification 함수 호출할 수 있도록 설정.

final class ViewController: UIViewController, KeyboardEvader {
 var keyboardScrollView: UIScrollView { return mainScrollView }
 override func viewDidLoad() {
  super.viewDidLoad()
  registerForKeyboardNotification()
 }
}

Extension이 아닌 Protocol를 사용한 이유?

Exit mobile version