一尘不染

在Swift中从userInfo获取键盘大小

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

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


阅读 259

收藏
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
}

或一步:

if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, 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, left: 0, bottom: keyboardSize.height, 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, left: 0, bottom: keyboardSize.height, right: 0)
    // ...
}
2020-07-07