Search code examples
iosautolayoutnslayoutconstraint

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


Let's say I have a UIView or UIViewController I want to use in many places throughout the app.

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.

If I wanted to achieve something like this in HTML/CSS, I would apply the following style:

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

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

I've tried using NSLayoutConstraints, but as far as I can tell I can only specify constraints relative to other views, which means I have to know where my view will be placed ahead of time.

Is there any way in iOS that I can specify "this view should be this tall and always be as far right as possible" without knowing the parent or surrounding views ahead of time?


Solution

  • 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.

    You have to wait until the view has a parent, but that's not difficult. Use a custom UIView subclass. In that subclass, override didMoveToSuperview, and in your override, create and activate the constraints. As you do that, refer to the view's superview as self.superview!; that's all your code needs to know.