从Swift中的userInfo获取键盘大小

前端之家收集整理的这篇文章主要介绍了从Swift中的userInfo获取键盘大小前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_502_0@ 我一直在试图添加一些代码来移动我的视图,当键盘出现,但是,我有问题,试图将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

这里是我目前有的代码

  1. override func viewWillAppear(animated: Bool) {
  2. NSNotificationCenter.defaultCenter().addObserver(self,selector: "keyboardWillShow:",name: UIKeyboardWillShowNotification,object: nil)
  3. NSNotificationCenter.defaultCenter().addObserver(self,selector: "keyboardWillHide:",name: UIKeyboardWillHideNotification,object: nil)
  4. }
  5.  
  6. override func viewWillDisappear(animated: Bool) {
  7. NSNotificationCenter.defaultCenter().removeObserver(self)
  8. }
  9.  
  10. func keyboardWillShow(notification: NSNotification) {
  11. var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
  12. UIEdgeInsets(top: 0,left: 0,bottom: keyboardSize.height,right: 0)
  13. let frame = self.budgetEntryView.frame
  14. frame.origin.y = frame.origin.y - keyboardSize
  15. self.budgetEntryView.frame = frame
  16. }
  17.  
  18. func keyboardWillHide(notification: NSNotification) {
  19. //
  20. }

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

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

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

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

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

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

  1. if let userInfo = notification.userInfo {
  2. if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
  3. let contentInsets = UIEdgeInsets(top: 0,right: 0)
  4. // ...
  5. } else {
  6. // no UIKeyboardFrameBeginUserInfoKey entry in userInfo
  7. }
  8. } else {
  9. // no userInfo dictionary in notification
  10. }

或在一个步骤:

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

Swift 3.0.1(Xcode 8.1)的更新:

  1. if let userInfo = notification.userInfo {
  2. if let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey] as? CGRect {
  3. let contentInsets = UIEdgeInsets(top: 0,right: 0)
  4. // ...
  5. } else {
  6. // no UIKeyboardFrameBeginUserInfoKey entry in userInfo
  7. }
  8. } else {
  9. // no userInfo dictionary in notification
  10. }

或在一个步骤:

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

猜你在找的Swift相关文章