How to center a subview of UIView

前端 未结 14 1836
無奈伤痛
無奈伤痛 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:28

    You can do this and it will always work:

    child.center = [parent convertPoint:parent.center fromView:parent.superview];
    

    And for Swift:

    child.center = parent.convert(parent.center, from:parent.superview)
    
    0 讨论(0)
  • 2020-11-30 17:28

    I would use:

    self.childView.center = CGPointMake(CGRectGetMidX(self.parentView.bounds),
                                        CGRectGetMidY(self.parentView.bounds));
    

    I like to use the CGRect options...

    SWIFT 3:

    self.childView.center = CGPoint(x: self.parentView.bounds.midX,
                                            y: self.parentView.bounds.midY);
    
    0 讨论(0)
  • 2020-11-30 17:28

    Using the same center in the view and subview is the simplest way of doing it. You can do something like this,

    UIView *innerView = ....;
    innerView.view.center = self.view.center;
    [self.view addSubView:innerView];
    
    0 讨论(0)
  • 2020-11-30 17:28

    I would use:

    child.center = CGPointMake(parent.bounds.height / 2, parent.bounds.width / 2)
    

    This is simple, short, and sweet. If you use @Hejazi's answer above and parent.center is set to anything other than (0,0) your subview will not be centered!

    0 讨论(0)
  • 2020-11-30 17:30

    The easiest way:

    child.center = parent.center
    
    0 讨论(0)
  • 2020-11-30 17:35

    You can use

    yourView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds))
    

    And In Swift 3.0

    yourView.center = CGPoint(x: superview.bounds.midX, y: superview.bounds.midY)
    
    0 讨论(0)
提交回复
热议问题