Ios 如果屏幕旋转,UIKeyboard将显示两次通知
我在键盘出现和消失时创建通知Ios 如果屏幕旋转,UIKeyboard将显示两次通知,ios,swift,swift2,nsnotificationcenter,Ios,Swift,Swift2,Nsnotificationcenter,我在键盘出现和消失时创建通知 override func viewDidLoad() { super.viewDidLoad() // Creates notification when keyboard appears and disappears NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboa
override func viewDidLoad() {
super.viewDidLoad()
// Creates notification when keyboard appears and disappears
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
self.adjustingHeight(true, notification: notification)
}
func keyboardWillHide(notification: NSNotification) {
self.adjustingHeight(false, notification: notification)
}
private func adjustingHeight(show: Bool, notification: NSNotification) {
// Gets notification information in an dictionary
var userInfo = notification.userInfo!
// From information dictionary gets keyboard’s size
let keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
// Gets the time required for keyboard pop up animation
let animationDurarion = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
// Animation moving constraint at same speed of moving keyboard & change bottom constraint accordingly.
if !(show && self.bottomConstraint.constant != self.bottomConstraintConstantDefault) {
if show {
self.bottomConstraint.constant = (CGRectGetHeight(keyboardFrame) + self.bottomConstraintConstantDefault / 2)
} else {
self.bottomConstraint.constant = self.bottomConstraintConstantDefault
}
UIView.animateWithDuration(animationDurarion) {
self.view.layoutIfNeeded()
}
}
self.hideLogoIfSmall()
}
当键盘已经显示并且我旋转屏幕时,就会出现这种奇怪的行为。然后发生下一个操作:
结果是我的视图没有正确更新,因为第一次调用UIKeyboardWillShowNotification时,我收到的键盘高度与第二次不同。最终我找到了解决方案。当我得到
keyboardFrame
时,我使用的是UIKeyboardFrameBeginUserInfoKey
,它在动画开始之前返回键盘的帧。正确的方法是使用UIKeyboardFrameEndUserInfoKey
在动画完成后返回键盘的帧
let keyboardFrame: CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
现在,
ui键盘将显示通知
被调用两次,但在两次调用中返回相同的键盘高度。这是正常行为,因为键盘在旋转前下降,旋转后再次上升。旋转后的高度可能不同,因此您应该根据新的高度更新代码。@HannesSverrisson所以您只提到一个向下和一个向上,还是说一个道指和两个向上?谢谢@汉内斯弗瑞森,因为我的行为是一败涂地up@WillM. 我发现的行为如下:我的设备是纵向的,键盘已经显示出来了。然后我旋转设备,然后键盘上下两次。@angeldev很可能是不相关的,但你设置观察者的方式很奇怪。您正在viewdiload
中创建它们,但在viewdiload
中删除它们。如果要在视图中删除它们,则应在视图中创建它们;如果要在视图中创建它们,则应在deinit中删除它们