【发布时间】:2018-05-21 18:30:31
【问题描述】:
问题:
我有一个 ViewController,它有一个包含 UIScrollView 的子类。
在scrollView中有3个UITextFields。其中 2 个带有数字键盘,1 个带有 UIPickerView 键盘。
问题是当键盘出现时,它隐藏了UITextFields。所以我要做的是在显示键盘时向上移动UIViewController 的视图。
我已经尝试过的:
我在 SO 上搜索了这个问题并找到了一些答案,基于这些答案我编写了以下代码:
override func viewDidLoad() {
super.viewDidLoad()
//Keyboard notifications
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//MARK: - keyboards
@objc fileprivate func keyboardWillShow(notification: Notification) {
self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}
@objc fileprivate func keyboardWillHide(notification: Notification) {
self.changeViewOriginBasedOnKeyboardPosition(notification: notification)
}
fileprivate func changeViewOriginBasedOnKeyboardPosition(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardAnimationDuration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
UIView.animate(withDuration: keyboardAnimationDuration != 0 ? keyboardAnimationDuration : 0.2, animations: {
if self.controllerContentView.frame.origin.y == 0 {
self.controllerContentView.frame.origin.y = -keyboardSize.height
} else {
self.controllerContentView.frame.origin.y = 0
}
})
}
}
fileprivate func dismissKeyboard() {
self.view.endEditing(true)
}
//Touch handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.dismissKeyboard()
}
我尝试过的问题:
有时效果很好,但有时视图“跳”回/“跳”下,我不明白为什么。
有人发现我的代码有什么问题会导致这个错误吗?
谢谢!
【问题讨论】:
-
您在
controllerContentView上设置了frame,但如果有自动布局更新,这些约束将接管。相反,更改controllerContentView的约束,然后在UIView.animate块内调用view.setNeedsLayout()。
标签: ios iphone swift cocoa-touch uitextfield