无法通过 ID 找到约束

Cannot find constraint by id

我有一个带 Center X Alignment Constraint 的按钮,此约束的 identifier"constBtnSound"

我正在尝试使用以下代码获取此 constraint 但无法找到它

for const in btnSound.constraints {
  if const.identifier == "constBtnSound" {
        ...
    }
}

约束的属性:

按钮的所有约束:

the UIView.addConstraint documentation 是这样说的:

The constraint must involve only views that are within scope of the receiving view. Specifically, any views involved must be either the receiving view itself, or a subview of the receiving view.

由于 button.superview 不是 button 并且不是 button 的子视图,因此约束 不能 由 [=13= 持有].

由于 buttonbutton.superview 的子视图,约束 可以 button.superview (或 [=12 的任何祖先=]).

但是,您可以为其创建一个出口,而不是通过 ID 搜索约束:

@IBOutlet var buttonXCenterConstraint: NSLayoutConstraint!

将出口连接到情节提要中的约束。