How to position activity indicator to the center of its superview using Auto Layout programmatically?

后端 未结 4 1797
终归单人心
终归单人心 2021-02-12 12:18

Why the following code does not work for positioning activity indicator to the center of its superview:

UIActivityIndicatorView *activityIndicator = [[UIActivity         


        
4条回答
  •  心在旅途
    2021-02-12 13:05

    It's meeting it's requirements by being in the corner, since you're not stating that the gaps on each side have to be the same. Try this instead:

    [self.superview addConstraint:[NSLayoutConstraint constraintWithItem:activityIndicator
                   attribute:NSLayoutAttributeCenterX 
                   relatedBy:NSLayoutRelationEqual 
                      toItem:self.superview 
                   attribute:NSLayoutAttributeCenterX 
                  multiplier:1.0 
                    constant:0.0]];
    

    And to center vertically do this too:

    [self.superview addConstraint:[NSLayoutConstraint constraintWithItem:activityIndicator
                   attribute:NSLayoutAttributeCenterY 
                   relatedBy:NSLayoutRelationEqual 
                      toItem:self.superview 
                   attribute:NSLayoutAttributeCenterY 
                  multiplier:1.0 
                    constant:0.0]];
    

    Alternatively, I highly recommend using the FLKAutoLayout project to simplify all this:

    https://github.com/dkduck/FLKAutoLayout

    Then you can do:

    [activityIndicator alignCenterXWithView:self.superview predicate:nil];
    [activityIndicator alignCenterYWithView:self.superview predicate:nil];
    

    Which is nice :)

提交回复
热议问题