【发布时间】:2017-05-27 02:24:36
【问题描述】:
当我开始编辑 UITextView 时,我正在使用此代码向上滚动视图。
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0{
self.view.frame.origin.y -= keyboardSize.height
}
}
}
func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
不过,我在这个视图的顶部还有一个UITextField,当我开始编辑它时,视图也会滚动。我不希望这种情况发生。如何将我的代码更改为仅在 UITextView 键盘处于活动状态时滚动,而不是在 UITextField 键盘被激活时滚动?
【问题讨论】:
-
不要通过键盘高度改变原点来盲目滚动。计算是否需要滚动以及滚动多少才能使新的第一响应者可见。
标签: ios swift keyboard uitextfield uitextview