【发布时间】:2016-02-01 17:10:16
【问题描述】:
我在键盘出现和消失时创建通知。
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()
}
当键盘已经显示并且我旋转屏幕时会发生奇怪的行为。然后发生下一个动作:
- UIKeyboardWillHideNotification 已调用
- 已调用 UIKeyboardWillShowNotification(使用旧的键盘高度)
- 调用 UIKeyboardWillShowNotification(使用新的键盘高度)
结果是我的视图没有正确更新,因为第一次调用 UIKeyboardWillShowNotification 我收到的键盘高度与第二次不同。
【问题讨论】:
-
这是正常现象,因为 keboard 在旋转前下降,旋转后又上升。旋转后的高度可能不同,所以你应该根据新的高度更新你的代码。
-
@HannesSverrisson 所以你只提到了一个下跌和一个上涨,还是你的意思是一个下跌和两个上涨?谢谢!
-
@HannesSverrisson 因为我的行为是一跌两涨
-
@WillM。我发现的行为如下:我的设备是纵向的,并且键盘已经显示。然后我旋转设备,然后键盘下降然后上升两次。
-
@angeldev 很可能是无关的,但你以一种奇怪的方式设置你的观察者。您在
viewDidLoad中创建它们,但在viewDidDisappear中删除它们。如果你要在viewDidDisappear中删除它们,你应该在viewDidAppear中创建它们,或者如果你要在viewDidLoad中创建它们,你应该在deinit中删除它们
标签: ios swift swift2 nsnotificationcenter