您的生产线存在一些问题
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(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}或一步:
if let keyboardSize = notification.userInfo?[UIKeyboardframeBeginUserInfoKey] as? CGRect { let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) // ...}


