Search code examples
iosautolayoutnslayoutconstraintuivisualeffectview

iOS Autolayout constraint between non-siblings


Is there a way to define a horizontal distance constraint between two views which are not siblings? I tried to add a constraint to their first common superview but the constraint doesn't seem to work.

The Apple documentation says:

The constraint may only reference the view itself or its subviews.

But I'm not sure if they meant direct subviews or not.

Rationale: I have a view where I want to put different children and arrange them. Some of those children should be shown with vibrancy effect. Unfortunately, enabling or disabling the vibrancy of a view in iOS is done through placing it in a UIVisualEffectView. So in order to have a mixture of vibrant and non-vibrant views I am using two containers in my top level view - one for vibrant views and the other for the rest. However, I need to arrange the visual items relative to each other with constraints. But since they are in different containers, I need the constraints to work for non-sibling views.


Solution

  • Unless you want to support the ~3% of users still on iOS 7, just don't manually add constraints to any view:

    When developing for iOS 8.0 or later, set the constraint’s active property to true instead. This automatically adds the constraint to the correct view.

    Create a constraint referring to both views, make sure they're in the same view hierarchy, activate it.