UIKeyboardAnimationDurationUserInfoKey返回极小的值

时间:2015-01-15 21:53:56

标签: xcode swift uikeyboard

func keyboardWillShow(notification:NSNotification){
    let userInfo = notification.userInfo
    let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as NSValue
    let keyboardSize = keyboardFrame.CGRectValue().size
    let animationDurationValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSValue
    var animationDuration : NSTimeInterval = 0
    animationDurationValue.getValue(&animationDuration)

    self.keyboardDelegate?.keyboardWillShowWithSize(keyboardSize, andDuration: animationDuration)
  }

在我的程序中,我尝试使用上述功能在键盘出现时重新定位我的视图。使用与我的objective-c代码中获得键盘动画持续时间相同的方法。这个给我以下状态:

duration 5.18065378653631e-315

这是一个非常小的值。我哪里做错了?请帮忙!

编辑:完整代码:

import Foundation
import UIKit

@objc protocol LPKeyboardViewControllerDelegate {
  func keyboardWillShowWithSize(size:CGSize, andDuration duration:NSTimeInterval)
  func keyboardWillHideWithSize(size:CGSize,andDuration duration:NSTimeInterval)
}

/**
This view controller will move up its view when a keyboard appears in its view
*/
class LPKeyboardViewController: UIViewController {
  var keyboardDelegate: LPKeyboardViewControllerDelegate?

  // MARK: - Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

    println("Start listening to keyboard")
  }

  func keyboardWillShow(notification:NSNotification){
    let userInfo = notification.userInfo
    let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as NSValue
    let keyboardSize = keyboardFrame.CGRectValue().size
    let animationDurationValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSValue
    var animationDuration : NSTimeInterval = 0
    animationDurationValue.getValue(&animationDuration)

    self.keyboardDelegate?.keyboardWillShowWithSize(keyboardSize, andDuration: animationDuration)
  }

  func keyboardWillHide(notification:NSNotification){
    let userInfo = notification.userInfo
    let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as NSValue
    let keyboardSize = keyboardFrame.CGRectValue().size
    let animationDurationValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
    var animationDuration : NSTimeInterval = animationDurationValue.doubleValue

    self.keyboardDelegate?.keyboardWillHideWithSize(keyboardSize, andDuration: animationDuration)

  }


}

1 个答案:

答案 0 :(得分:3)

文档说明此密钥的对象是NSNumber,因此您不必跳过您可以做的箍

let animationDurationValue = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSNumber
let animationDuration      = animationDurationValue.doubleValue