小编典典

在Swift中从userInfo获取键盘大小Getting keyboard size from userInfo in Swift

swift

我一直在尝试添加一些代码以在键盘
出现时向上移动视图,但是,在尝试将Objective-C
示例转换为Swift 时遇到了问题。我已经取得了一些进步,但是我仍然停留在一条
特定的线上。

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

如何使用
Swift http://www.ioscreator.com/tutorials/move-view-when-keyboard-appears 在键盘出现时向上移动UIViewController的内容

这是我目前拥有的代码:

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))

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


阅读 353

收藏
2020-07-07

共1个答案

小编典典

您的生产线存在一些问题

    var keyboardSize = notification.userInfo(valueForKey(UIKeyboardFrameBeginUserInfoKey))
  • notification.userInfo返回一个可选的 dictionary [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
}

or in one step:

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

Update for 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
}

or in one step:

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