从Swift中的userInfo获取键盘大小

use*_*428 78 uikeyboard swift

我一直在尝试添加一些代码来在键盘出现时移动我的视图,但是,我在尝试将Objective-C示例转换为Swift时遇到了问题.我取得了一些进展,但我被困在一条特定的路线上.

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

当Keypad使用Swift出现时,如何向上移动UIViewController的内容 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) {
    //
}
Run Code Online (Sandbox Code Playgroud)

目前,我在这一行收到错误:

var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
Run Code Online (Sandbox Code Playgroud)

如果有人能让我知道这行代码应该是什么,我应该设法自己弄清楚其余部分.

Mar*_*n R 182

您的生产线存在一些问题

var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
Run Code Online (Sandbox Code Playgroud)
  • 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, left: 0, bottom: keyboardSize.height, right: 0)
       // ...
   } else {
       // no UIKeyboardFrameBeginUserInfoKey entry in userInfo
   }
} else {
   // no userInfo dictionary in notification
}
Run Code Online (Sandbox Code Playgroud)

或者一步到位:

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    // ...
}
Run Code Online (Sandbox Code Playgroud)

Swift 3.0.1(Xcode 8.1)的更新:

if let userInfo = notification.userInfo {
    if let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
        let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
        // ...
    } else {
        // no UIKeyboardFrameBeginUserInfoKey entry in userInfo
    }
} else {
    // no userInfo dictionary in notification
}
Run Code Online (Sandbox Code Playgroud)

或者一步到位:

if let keyboardSize = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    // ...
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*las 18

对于更少的代码,考虑一下这个

这对我很有帮助.您只需在视图控制器中包含视图约束并使用您添加的两个观察者.然后只需使用以下方法(这里假设你移动一个tableView)

func keyboardWillShow(sender: NSNotification) {
        if let userInfo = sender.userInfo {
            if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height {
                tableViewBottomConstraint.constant = keyboardHeight
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.view.layoutIfNeeded()
                })
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

func keyboardWillHide(sender: NSNotification) {
if let userInfo = sender.userInfo {
  if let keyboardHeight = userInfo[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size.height {
    tableViewBottomConstraint.constant = 0.0
    UIView.animateWithDuration(0.25, animations: { () -> Void in self.view.layoutIfNeeded() })
  }
} }
Run Code Online (Sandbox Code Playgroud)


Dud*_*ock 11

如果您使用的是故事板,而不是操纵视图本身,则可以利用自动布局.

(这是尼古拉斯答案的清理版)

设置通知中心以通知您键盘的外观和消失:

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

}
Run Code Online (Sandbox Code Playgroud)

并确保在不再需要时删除观察者:

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: self.view.window)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: self.view.window)
}
Run Code Online (Sandbox Code Playgroud)

在故事板内部,设置底部约束.创建该约束的出口:

在此输入图像描述

并在显示或隐藏键盘时设置约束的常量属性:

func keyboardWillShow(notification: NSNotification) {
    guard let keyboardHeight = (notification.userInfo! as NSDictionary).objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size.height else {
        return
    }
    nameOfOutlet.constant = keyboardHeight
    view.layoutIfNeeded()
}

func keyboardWillHide(notification: NSNotification) {
    nameOfOutlet.constant = 0.0
    view.layoutIfNeeded()
}
Run Code Online (Sandbox Code Playgroud)

现在,每当键盘出现或消失时,autolayout将会处理所有事情.