Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
final class ViewController: UIViewController {
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// avoid keyboard.
NotificationCenter.default.rx.notification(UIResponder.keyboardWillChangeFrameNotification)
.bind(onNext: { [view, bottomConstraint] notification in
adjust(view: view, notification: notification, bottomLayoutConstraint: bottomConstraint, buffer: 0)
})
.disposed(by: disposeBag)
}
}
private func adjust(view: UIView?, notification: Notification, bottomLayoutConstraint: NSLayoutConstraint?, buffer: CGFloat) {
guard let view = view else { return }
guard let bottomLayoutConstraint = bottomLayoutConstraint else { return }
guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
guard let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval else { return }
view.layoutIfNeeded()
let window = UIApplication.shared.keyWindow
let bottomPadding = window?.safeAreaInsets.bottom ?? 0
UIView.animate(withDuration: duration, animations: {
bottomLayoutConstraint.constant = UIScreen.main.bounds.height - keyboardFrame.minY + buffer - bottomPadding
view.layoutIfNeeded()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment