How to center a subview of UIView

前端 未结 14 1924
無奈伤痛
無奈伤痛 2020-11-30 16:47

I have a UIView inside a UIViewm and I want the inner UIView to be always centered inside the outer one, without it having to resize t

14条回答
  •  一生所求
    2020-11-30 17:19

    1. If you have autolayout enabled:

    • Hint: For centering a view on another view with autolayout you can use same code for any two views sharing at least one parent view.

    First of all disable child views autoresizing

    UIView *view1, *view2;
    [childview setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    1. If you are UIView+Autolayout or Purelayout:

      [view1 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:view2];
      [view1 autoAlignAxis:ALAxisVertical toSameAxisOfView:view2];
      
    2. If you are using only UIKit level autolayout methods:

      [view1 addConstraints:({
          @[ [NSLayoutConstraint
             constraintWithItem:view1
             attribute:NSLayoutAttributeCenterX
             relatedBy:NSLayoutRelationEqual
             toItem:view2
             attribute:NSLayoutAttributeCenterX
             multiplier:1.f constant:0.f],
      
             [NSLayoutConstraint
              constraintWithItem:view1
              attribute:NSLayoutAttributeCenterY
              relatedBy:NSLayoutRelationEqual
              toItem:view2
              attribute:NSLayoutAttributeCenterY
              multiplier:1.f constant:0.f] ];
      })];
      

    2. Without autolayout:

    I prefer:

    UIView *parentView, *childView;
    [childView setFrame:({
        CGRect frame = childView.frame;
    
        frame.origin.x = (parentView.frame.size.width - frame.size.width) / 2.0;
        frame.origin.y = (parentView.frame.size.height - frame.size.height) / 2.0;
    
        CGRectIntegral(frame);
    })];
    

提交回复
热议问题