Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Created October 21, 2019 17:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danielt1263/6cc593e5f213afbb2a8fb860dab304ce to your computer and use it in GitHub Desktop.
Save danielt1263/6cc593e5f213afbb2a8fb860dab304ce to your computer and use it in GitHub Desktop.
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