import SnapKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
.receive(on: DispatchQueue.main)
.sink { notification in
let info = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
let keyboardHeight = info?.cgRectValue.height
guard let keyboardHeight else { return }
self.button.snp.remakeConstraints {
$0.height.equalTo(60)
$0.bottom.equalToSuperview().offset(-keyboardHeight)
$0.width.equalToSuperview()
$0.centerX.equalToSuperview()
}
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}.store(in: &cancellables)
NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)
.receive(on: DispatchQueue.main)
.sink { _ in
self.button.snp.remakeConstraints {
$0.height.equalTo(100)
$0.bottom.equalToSuperview()
$0.width.equalToSuperview()
$0.centerX.equalToSuperview()
}
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}.store(in: &cancellables)
}
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}