I'm trying to move up a UIButton when the keyboard is shown. So when the keyboard is shown, the UIButton moves up 20px above the keyboard at the same time the keyboard animation is shown so it look like the button is connected to the keyboard. So I need to determine the size of the keyboard so I can apply that to the button event. Here is my code:
@objc func keyboardWillChange(notification: Notification) {
if notification.name == UIResponder.keyboardWillShowNotification || notification.name == UIResponder.keyboardWillChangeFrameNotification {
nextBtn.frame.origin.y = view.frame.maxY - 300
} else {
nextBtn.frame.origin.y = 0
}
}
I have a few problems with my code:
class Start_EmailVC: UIViewController, UITextFieldDelegate {
var checkValid = CheckValid()
@IBOutlet weak var nextBtn: UIButton!
@IBOutlet weak var emailTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//Next Button Auth
nextBtn.alpha = 0.5
nextBtn.isEnabled = false
hideIt()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardShown), name: UIResponder.keyboardWillShowNotification, object: nil);
}
@objc func keyboardShown(notification: NSNotification) {
let info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
print("keyboardFrame: \(keyboardFrame)")
}
func hideIt() {
//Listen For Keyboard Events
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
deinit {
//Stop Listening for keyboard hide/show events
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
@objc func keyboardWillChange(notification: Notification) {
if notification.name == UIResponder.keyboardWillShowNotification || notification.name == UIResponder.keyboardWillChangeFrameNotification {
nextBtn.frame.origin.y = view.frame.maxY - 300
} else {
nextBtn.frame.origin.y = 0
}
}}
The button does push up but not the same time as the keyboard and it just doesn't look good.