从Swift中的userInfo获取键盘大小

前端之家收集整理的这篇文章主要介绍了从Swift中的userInfo获取键盘大小前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在试图添加一些代码来移动我的视图,当键盘出现,但是,我有问题,试图将Objective-C的例子翻译成Swift。我已经取得了一些进展,但我被困在一条线。

这是我一直在关注的两个教程/问题:

How to move content of UIViewController upwards as Keypad appears using Swift
http://www.ioscreator.com/tutorials/move-view-when-keyboard-appears

这里是我目前有的代码

override func viewWillAppear(animated: Bool) {
    NSNotificationCenter.defaultCenter().addObserver(self,selector: "keyboardWillShow:",name: UIKeyboardWillShowNotification,object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self,selector: "keyboardWillHide:",name: UIKeyboardWillHideNotification,object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

func keyboardWillShow(notification: NSNotification) {
    var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
    UIEdgeInsets(top: 0,left: 0,bottom: keyboardSize.height,right: 0)
    let frame = self.budgetEntryView.frame
    frame.origin.y = frame.origin.y - keyboardSize
    self.budgetEntryView.frame = frame
}

func keyboardWillHide(notification: NSNotification) {
    //
}

目前,我在这行上得到一个错误

var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))

如果有人可以让我知道这行代码应该是什么,我应该设法弄清楚其余的自己。

在你的线有一些问题
var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))

> notification.userInfo返回一个可选的字典[NSObject:AnyObject]?
因此在访问其值之前必须将其解包。
> Objective-C NSDictionary映射到一个Swift本地词典,所以你必须
使用字典下标语法(dict [key])来访问值。
>该值必须转换为NSValue,以便可以对其调用CGRectValue。

所有这一切都可以通过可选的赋值,可选的链接
可选转换:

if let userInfo = notification.userInfo {
   if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    let contentInsets = UIEdgeInsets(top: 0,right: 0)
       // ...
   } else {
       // no UIKeyboardFrameBeginUserInfoKey entry in userInfo
   }
} else {
   // no userInfo dictionary in notification
}

或在一个步骤:

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    let contentInsets = UIEdgeInsets(top: 0,right: 0)
    // ...
}

Swift 3.0.1(Xcode 8.1)的更新:

if let userInfo = notification.userInfo {
    if let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
        let contentInsets = UIEdgeInsets(top: 0,right: 0)
        // ...
    } else {
        // no UIKeyboardFrameBeginUserInfoKey entry in userInfo
    }
} else {
    // no userInfo dictionary in notification
}

或在一个步骤:

if let keyboardSize = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
    let contentInsets = UIEdgeInsets(top: 0,right: 0)
    // ...
}

猜你在找的Swift相关文章