2017-10-07 79 views
0

我试图在键盘显示和隐藏时移动滚动视图内容。我正在做基本功能。 但键盘首先可见并且向上移动的动画被延迟,并且在更新到ios 11之后它具有更多的延迟。键盘动画延迟

代码:

viewDidLoad(){ 
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardNotification(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) 
} 

@objc func keyboardNotification(notification: NSNotification) { 


     if let userInfo = notification.userInfo { 
      let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue 
      let duration:TimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 
      let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber 
      let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue 
      let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw) 
      if (endFrame?.origin.y)! >= UIScreen.main.bounds.size.height { 
       self.keyboardHeightLayoutConstraint?.constant = 0.0 
      } else { 
       self.keyboardHeightLayoutConstraint?.constant = endFrame?.size.height ?? 0.0 
      } 
      UIView.animate(withDuration: duration, 
          delay: TimeInterval(0), 
          options: animationCurve, 
          animations: { self.view.layoutIfNeeded() }, 
          completion: nil) 
     } 
    } 

keyboardHeightLayoutConstraint是滚动型的底部约束。

我在做什么错了?任何帮助,将不胜感激。谢谢!

+0

使用'UIKeyboardDidChangeFrame'键键盘动画。为了更好的实现,你可以看看这个博客http://eng.moldedbits.com/technical/ios/2017/08/28/typed-notification-ios.html – Aks

+0

@Aks我正在使用UIKeyboardWillChangeFrame。不好吗? –

+0

'WillChange'在框架更改之前发布,请检查此Apple文档以获取关于键盘的不同通知: - https://developer.apple.com/documentation/uikit/uiwindow – Aks

回答

0

尝试这个给滚动视图的高度,并与主视图高度计算 - 键盘的高度和keyboardchangeframe将工作延迟,如果你想捕捉键盘打开和隐藏你应该viewDidLoad中添加这些到:

全球的:var keyboardHeight :CGFloat的?

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) 
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) 

,当负荷计算出滚动视图高度

self.scrollviewHeight.constant = self.view.frame.height - keyboardHeight - self.textView.frame.height 

就可以计算出这样的具有UIView.animation