二元运算符“+”不能应用于类型 'CGRect' 和 'Double'

Binary Operator '+' cannot be applied to type 'CGRect' and 'Double'

我正在尝试更改按钮的底部常量,当键盘出现到键盘的高度时增加 8 个点。

然而下面

if let keyboardHeight = (n.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

   saveButtonBottomConstant.constant = keyboardHeight + 8.0
}

在 Xcode 8.0 beta 6 转换为 Swift 3

时出现以下错误

Binary Operator '+' cannot be applied to type 'CGRect' and 'Double'

我明白为什么会这样,但是我的尝试导致的错误比解决问题的错误更多。

如何简单地将 Double 添加到 Swift 3 中的 CGRect 值?

UIKeyboardFrameBeginUserInfoKey returns 屏幕坐标中的键盘框架,因此 keyboardHeightCGRect 类型。

您可以通过以下方式获取键盘的高度:

if let keyboardFrame = (n.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
  saveButtonBottomConstant.constant = keyboardFrame.height + 8.0
}

您应该有 2 个 Double 值或 2 个 GCRect 值。将其中一个换成另一个再试一次。

您的代码将无法运行,因为您试图将 Double (8.0) 添加到 CGRect (keyboardHeight)。由于您正在使用 Swift 3 CGRectGetHeight() 不可用,因此您应该使用此:

saveButtonBottomConstant.constant = keyboardHeight.height + 8.0