我正在尝试在显示键盘时向上移动UIButton。因此,当显示键盘时,UIButton在显示键盘动画的同时向上移动键盘上方20px,因此看起来按钮已连接到键盘。因此,我需要确定键盘的大小,以便可以将其应用于按钮事件。 这是我的代码:
@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
}
}
我的代码有一些问题:
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
}
}}
该按钮确实向上推,但与键盘不同,只是外观不太好。