Auto Layout (Constraints) Center 2 side by side views in a parent view

前端 未结 8 1318
小蘑菇
小蘑菇 2020-12-12 12:35

I\'m trying to figure out how to do this with auto layout (iOS6) and constraints.

Basically I have my large view divided up into two sections on the bottom. Inside o

相关标签:
8条回答
  • 2020-12-12 13:20

    I figured out a way without adding another view:

     [aView addConstraint:[NSLayoutConstraint constraintWithItem:viewOnLeft attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationLessThanOrEqual toItem:aView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
     [aView addConstraint:[NSLayoutConstraint constraintWithItem:viewOnRight attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationLessThanOrEqual toItem:aView attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
    

    You can also change the constants to create a gap between the views.

    • left view constraint constant: -X
    • right view constraint constant: +X

    centering subviews

    0 讨论(0)
  • 2020-12-12 13:23

    There are several ways to do this. In basic terms, here is how to center 1..n items, assuming all your items have constrained sizes and are not going to grow.

    1. Put 2 spacers on each side of your items. Anchor the spacers to the parent edges. Anchor your first and last items to the anchors. Finally, assign 1 spacer to have the width of the other spacer. You do not need to explicitly set any spacer size, as it will be solved.

      • spacer1 -> left=parent:left width=spacer2:width
      • spacer2 -> right=parent:right
      • yourFirstItem -> left=spacer1:right
      • yourLastItem -> right=spacer2:left
    2. If spacers aren't your thing, and you and you have an odd number of items, center the middle one to the center of the parent. Also, make sure the first and last items are not anchored to the parent edges.

      • yourMiddleItem = centerX=parent:centerX
      • otherItems->yourMiddleItem<-otherItems
    3. If spacers aren't your thing, and you have an even number of items, center the 2 inner items' edges to the center of the parent. Also, make sure the first and last items are not anchored to the parent edges.

      • leftMiddleItem -> right=parent:centerX
      • rightMiddleItem -> left=parent:centerX
      • otherItems->leftMiddleItem rightMiddleItem<-otherItems
    4. You can also center an invisible placeholder in the center, and anchor to that, but you will still need to consider an odd/even number of items when constraining, so I don't recommend that approach.

    0 讨论(0)
提交回复
热议问题