iOS - Position UIView in center of superview using Auto Layout programmatically

后端 未结 2 1657
庸人自扰
庸人自扰 2020-12-08 07:24

How do you programmatically set a UIView to be in the center of its superview using Auto Layout?

UIButton* viewObj = [UIButton buttonWithType:UIButtonTypeRo         


        
2条回答
  •  误落风尘
    2020-12-08 08:14

    Since you asked this question in the context of using Auto Layout, the issue here is that a UIButton has an intrinsic size (communicated through the intrinsicContentSize method) that provides Auto Layout with information about width and height, but a UIView normally does not. So you need to add more constraints related to width and height.

    If you want your UIView to be a set size (say, 200x200), you could add these lines:

    cn = [NSLayoutConstraint constraintWithItem:viewObj 
                                      attribute:NSLayoutAttributeHeight
                                      relatedBy:NSLayoutRelationEqual 
                                         toItem:nil
                                      attribute:NSLayoutAttributeNotAnAttribute 
                                     multiplier:1
                                       constant:200];
    [viewObj addConstraint:cn];
    
    cn = [NSLayoutConstraint constraintWithItem:viewObj
                                      attribute:NSLayoutAttributeWidth
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:nil
                                      attribute:NSLayoutAttributeNotAnAttribute 
                                     multiplier:1 
                                       constant:200];
    [viewObj addConstraint: cn];
    

    Note that the toItem: argument is nil and the second attribute is NSLayoutAttributeNotAnAttribute, because you aren't specifying the width and height relative to anything else. If you want the subview's height and width to be relative to the superview (say, 0.5), you could do this:

    cn = [NSLayoutConstraint constraintWithItem:viewObj
                                      attribute:NSLayoutAttributeHeight
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:self.view
                                      attribute:NSLayoutAttributeHeight 
                                     multiplier:0.5 
                                       constant:0];
    [self.view addConstraint:cn];
    cn = [NSLayoutConstraint constraintWithItem:viewObj
                                      attribute:NSLayoutAttributeWidth
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:self.view
                                      attribute:NSLayoutAttributeWidth
                                     multiplier:0.5
                                       constant:0];
    [self.view addConstraint: cn];
    

提交回复
热议问题