您的生产线存在一些问题
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 (Xpre 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) // ...}


