是否可以定义与未知 UIView 相关的自动布局约束?

Is it possible to define auto layout constraints relative to unknown UIViews?

假设我有一个 UIView 或 UIViewController,我想在整个应用程序的许多地方使用它。

虽然我不知道它最终将如何显示或显示在何处,但我知道我总是希望它的宽度是其父级的一半,并固定在右侧。

如果我想在 HTML/CSS 中实现类似的效果,我会应用以下样式:

.floatRight{
  position: relative;
  width: 50%;
  float: right;
}

<div class="floatRight"> foobar </div>

我试过使用 NSLayoutConstraints,但据我所知,我只能指定相对于其他视图的约束,这意味着我必须提前知道我的视图将放置在哪里。

在 iOS 中有什么方法可以指定 "this view should be this tall and always be as far right as possible" 而无需提前知道父视图或周围视图?

While I don't know how or where it'll ultimately be displayed, I know I always want it to have half the width of its parent, and be pinned to the right.

您必须等到视图有父视图,但这并不困难。使用自定义 UIView 子类。在该子类中,覆盖 didMoveToSuperview,并在您的覆盖中创建并激活约束。当你这样做时,将视图的父视图引用为 self.superview!;这就是您的代码需要知道的全部内容。