Search code examples
iosautolayoutios-autolayout

Autolayout: keep view's centerX same with another View but not overstep its superView


There are two subviews in yellow view: red view and green view. Both of them have fixed width and height. greenView has two more constraint: leading and bottom to the yellow View. redView has two more constraint: vertical space between bottom to the greenView's top and same centerX with greenView. (Figure 1)enter image description here (Figure 1)

What I need to do is, always keep redView inside of the yellow View, even if green view's leading constraint to the yellow view is Zero.(Figure 2) What should I do with AutoLayout? Any idea? Thanks. enter image description here(Figure 2)


Solution

  • Sample

    This example makes 3 constraints to the orange view:

    1. Leading space >= 0 (priority 1000)
    2. Trailing Space >= 0 (priority 1000)
    3. CenterX to the green box (priority 999)
    

    Result: (I forgot to remove the margin) Sample2