我正在使用Swift 4在iOS应用程序上工作。在该项目中,我创建了动态TextField。当我单击TextField时,我添加了UIScrollView,当键盘出现时,滚动视图应向上移动,而当键盘消失时,滚动视图应向下移动。以下代码仅在第一次单击时有效。从第二次开始,它不起作用。当我编辑文本字段键盘时,但滚动条没有向上移动。
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var constraintContentHeight: NSLayoutConstraint!
var activeField: UITextField?
var lastOffset: CGPoint!
var keyboardHeight: CGFloat!
在ViewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// Add touch gesture for contentView
self.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(returnTextView(gesture:))))
@objc func keyboardWillShow(notification: NSNotification) {
if keyboardHeight != nil {
return
}
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
keyboardHeight = keyboardSize.height
// so increase contentView's height by keyboard height
UIView.animate(withDuration: 0.3, animations: {
self.constraintContentHeight.constant += self.keyboardHeight
})
// move if keyboard hide input field
let distanceToBottom = self.myScroll.frame.size.height - (activeField?.frame.origin.y)! - (activeField?.frame.size.height)!
let collapseSpace = keyboardHeight - distanceToBottom
if collapseSpace < 0 {
// no collapse
return
}
// set new offset for scroll view
UIView.animate(withDuration: 0.3, animations: {
// scroll to the position above keyboard 10 points
self.myScroll.contentOffset = CGPoint(x: self.lastOffset.x, y: collapseSpace + 10)
})
}
}
@objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.3) {
self.constraintContentHeight.constant -= self.keyboardHeight
self.myScroll.contentOffset = self.lastOffset
}
keyboardHeight = nil
}
@objc func returnTextView(gesture: UIGestureRecognizer) {
guard activeField != nil else {
return
}
activeField?.resignFirstResponder()
activeField = nil
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
activeField = textField
lastOffset = self.myScroll.contentOffset
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
activeField?.resignFirstResponder()
activeField = nil
return true
}
任何人都可以帮助我解决此问题。我在这里犯了什么错误?
谢谢。