[swift] RxCocoa를 활용한 키보드 이벤트 처리 방법

RxCocoa를 사용하면 Swift 프로젝트에서 간단하게 키보드 이벤트를 처리할 수 있습니다. 이번 글에서는 RxCocoa를 사용하여 키보드의 올라오고 내려오는 이벤트를 감지하는 방법을 알아보겠습니다.

1. RxCocoa 설치

RxCocoa를 사용하기 위해서는 먼저 CocoaPods 또는 Swift Package Manager를 통해 RxCocoa를 설치해야 합니다.

CocoaPods를 사용하는 경우:

Podfile에 다음과 같은 내용을 추가하고, pod install 명령어를 실행합니다.

pod 'RxCocoa'

Swift Package Manager를 사용하는 경우:

Package.swift 파일에 다음과 같은 종속성을 추가합니다.

dependencies: [
    .package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "6.0.0")),
    .package(url: "https://github.com/ReactiveX/RxCocoa.git", .upToNextMajor(from: "6.0.0")),
],
targets: [
    .target(name: "YourTarget", dependencies: ["RxCocoa", "RxSwift"]),
]

2. RxCocoa를 이용한 키보드 이벤트 처리

RxCocoa를 사용하여 키보드 이벤트를 처리하는 방법은 아래와 같습니다.

import UIKit
import RxCocoa
import RxSwift

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    
    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 키보드 올라오는 이벤트를 구독하고 처리합니다.
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
            .subscribe(onNext: { [weak self] notification in
                // 키보드 높이를 가져옵니다.
                guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
                    return
                }
                
                // 키보드 높이에 맞춰 뷰를 이동시킵니다.
                self?.view.frame.origin.y -= keyboardFrame.height
            })
            .disposed(by: disposeBag)
        
        // 키보드 내려가는 이벤트를 구독하고 처리합니다.
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification)
            .subscribe(onNext: { [weak self] _ in
                // 뷰를 원래 위치로 되돌립니다.
                self?.view.frame.origin.y = 0
            })
            .disposed(by: disposeBag)
    }
}

위의 예제 코드에서는 UIResponder.keyboardWillShowNotificationUIResponder.keyboardWillHideNotification 이벤트를 RxCocoa를 통해 구독하고, 이벤트 발생 시 뷰의 위치를 조정하는 방법을 보여줍니다.

참고 자료