从Swift中的userInfo获取键盘大小
我一直在试图添加一些代码来移动我的视图,当键盘出现,但是,我有问题,试图将Objective-C的例子翻译成Swift。我已经取得了一些进展,但我被困在一条线。
这是我一直在关注的两个教程/问题: How to move content of UIViewController upwards as Keypad appears using Swift 这里是我目前有的代码: 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]? 所有这一切都可以通过可选的赋值,可选的链接和 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) // ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |