gpt4 book ai didi

ios - 如果屏幕旋转,KeyboardWillShowNotification 会调用两次

转载 作者:可可西里 更新时间:2023-10-31 23:49:19 32 4
gpt4 key购买 nike

我会在键盘出现和消失时创建通知。

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()

}

当键盘已经显示并且我旋转屏幕时会出现奇怪的行为。然后发生下一个 Action :

  1. 已调用 UIKeyboardWillHideNotification
  2. 调用了 UIKeyboardWillShowNotification(使用键盘的旧高度)
  3. 调用了 UIKeyboardWillShowNotification(使用新的键盘高度)

结果是我的 View 没有正确更新,因为第一次调用 UIKeyboardWillShowNotification 时我收到的键盘高度与第二次不同。

最佳答案

终于找到了解决办法。当我得到 keyboardFrame 时,我使用的是 UIKeyboardFrameBeginUserInfoKey,它会在动画开始之前返回键盘的框架。正确的做法是使用 UIKeyboardFrameEndUserInfoKey,它会在动画完成后返回键盘的框架。

let keyboardFrame: CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

现在 UIKeyboardWillShowNotification 被调用了两次,但在两次调用中返回了相同的键盘高度。

关于ios - 如果屏幕旋转,KeyboardWillShowNotification 会调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136311/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com