【发布时间】:2018-08-25 13:26:15
【问题描述】:
我试图在键盘出现时创建相应的文本字段应该移动到键盘顶部,这里有两件事我需要解决,在编辑时间文本字段到起点时,我还需要在子类中使用下面的代码,因为想要得到由多个其他类文本字段引用。
这里,在我的代码下面
extension UIView {
func bindToKeyboard(){
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
func unbindFromKeyboard(){
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
@objc
func keyboardWillChange(notification: NSNotification) {
guard let userInfo = notification.userInfo else { return }
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! UInt
let curFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let targetFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
})
}
}
在 Viewdidload 中
baseview.bindToKeyboard()
文本字段应该返回
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.baseview.endEditing(true)
return false
}
【问题讨论】: