Skip to content

Instantly share code, notes, and snippets.

@Slowhand0309
Last active July 27, 2019 05:37
Show Gist options
  • Save Slowhand0309/480c1694249fc636ea73b969ac03ea9e to your computer and use it in GitHub Desktop.
Save Slowhand0309/480c1694249fc636ea73b969ac03ea9e to your computer and use it in GitHub Desktop.
[Keyboard Event With RxSwift] #iOS
import RxSwift
import RxCocoa
class ViewController: UIViewController {
@IBOutlet private weak var bottomConstraint: NSLayoutConstraint!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.rx.notification(UIView.keyboardWillShowNotification)
.subscribe(onNext: { notification in
self.keyboardWillShow(notification)
})
.disposed(by: disposeBag)
NotificationCenter.default.rx.notification(UIView.keyboardWillHideNotification)
.subscribe(onNext: { notification in
self.keyboardWillHide(notification)
})
.disposed(by: disposeBag)
}
// MARK: - keyboard event
@objc private func keyboardWillShow(_ notification: Notification) {
guard let userInfo = notification.userInfo as? [String: Any] else { return }
guard let keyboardInfo = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardSize = keyboardInfo.cgRectValue.size
var safeAreaBottom: CGFloat = 0
if #available(iOS 11.0, *) {
safeAreaBottom = self.view.safeAreaInsets.bottom
}
bottomConstraint.constant = keyboardSize.height - safeAreaBottom
}
@objc private func keyboardWillHide(_: Notification) {
bottomConstraint.constant = 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment