我有一个包含4个文本字段和一个按钮的视图..这个视图不是主视图..问题是键盘覆盖了文本字段和按钮!
我尝试了这段代码,但它不起作用:
// Move the text field in a pretty animation!
func moveTextField(_ textField: UITextField, moveDistance: Int, up: Bool) {
let moveDuration = 0.3
let movement: CGFloat = CGFloat(up ? moveDistance : -moveDistance)
if textField.tag>=2{
UIView.beginAnimations("animateTextField", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(moveDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()}
}
我已经为它们设置了从0到4的标签号......
我在viewDidLoad中设置了委托:
fname.delegate=self
email.delegate=self
mobile1.delegate=self
mobile2.delegate=self
但这不起作用仍然键盘将覆盖文本字段和按钮!为什么?以及如何解决它?
更新:
我想我发现了问题......我试过这个:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidChangeFrame, object: nil)
}
@objc func keyboardWillChange(notification: Notification){
guard let keyboardRect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else{
return
}
if activeTF.tag >= 2 {
if notification.name == Notification.Name.UIKeyboardDidShow || notification.name == Notification.Name.UIKeyboardDidChangeFrame {
view.frame.origin.y = -keyboardRect.height
}else{
view.frame.origin.y = 0
}
}
}
with:
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
textField.resignFirstResponder()
return true
}
这两个功能完美无缺......但是当我将其更改为:
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
// Try to find next responder
if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
textField.resignFirstResponder()
}
//do not add a line break
return false
}
只有maketextfieldreturn可以工作,而且keyboardwillchange不起作用!为什么呢?