我一直在尝试添加一些代码以在键盘出现时向上移动视图,但是,在尝试将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))
如果有人能让我知道这行代码应该是什么,我应该自己弄清楚其余的代码。
您的生产线存在一些问题
notification.userInfo
[NSObject : AnyObject]?
NSDictionary
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) // ... }