'UIView' 类型的值没有成员 'constant'

Value of type 'UIView' has no member 'constant'

@objc  func handleKeyboardDidShow (notification: NSNotification)
{
    let keyboardRectAsObject = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue

    var keyboardRect = CGRect.zero

    keyboardRectAsObject.getValue(&keyboardRect)

    self.changePassView.constant = -1 * keyboardRect.height/2

    UIView.animate(withDuration: 0.5,animations: {

        self.view.layoutIfNeeded()

    })
}

谁能帮帮我?为什么我是 iOS 和学习这门语言的初学者时会收到此错误。

self.changePassView.constant = -1 * keyboardRect.height/2

您收到错误是因为您试图访问 self.changePassView 中名为 constant 的 属性,这显然是 UIView。看起来您正在尝试更改视图底部约束的值,但布局约束是一个单独的对象,您必须先获取它才能设置它的值。这可能会有所帮助:

UIViews包含了自己的外貌和内容等信息。

NSLayoutConstraints 通常添加到 UIView 以修改它们在屏幕上的分布方式。

您收到错误消息是因为您试图访问 属性、constant,但在 UIViews 中找不到。不过你很接近。你需要一个NSLayoutConstraint.

第 1 步:设置约束

您可以通过编程方式 (read more here) 或借助故事板/nib 来执行此操作。这是 storyboard/nib 方法的分步说明:

  1. 使用自动布局在故事板或 nib 中添加约束。
  2. 在您的 UIView class 中创建一个 NSLayoutConstraint 变量 class。
  3. 返回故事板,找到新创建的约束。它会显示在左侧的视图导航器中,在 UIView.
  4. 旁边
  5. Select 您要查找的约束,然后导航至 Xcode 右侧面板的最右侧选项卡。
  6. 将 "New Referencing Outlet" 从右侧面板拖到视图导航器中的 UIViewController class。
  7. 如果操作正确,将出现新 NSLayoutConstraint 的选项。 Select它。

现在你代码中的变量引用了你在视觉上所做的约束。如果这些步骤令人困惑并且您是初学者(我不太清楚),请参考 this thorough guide 故事板。

第 2 步:组合

访问您的 NSLayoutConstraintconstant 值。完成上述所有步骤后,您的代码应如下所示:

// In your class's definitions.
// This is what you'll have to link programmatically or in your storyboard/nib
@IBOutlet var changePassViewBottomConstraint: NSLayoutConstraint!

// Later on in your function:
self.changePassViewBottomConstraint.constant = -1 * keyboardRect.height/2