Why the following code does not work for positioning activity indicator to the center of its superview:
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[self.mysuperview addSubview:activityIndicator];
[activityIndicator addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"|-(>=20)-[view(==100)]-(>=20)-|"
options:NSLayoutFormatAlignAllCenterX | NSLayoutFormatAlignAllCenterY
metrics:nil
views:@{@"view" : self.mysuperview}]];
Activity indicator is positioned somewhere at the top left corner, definitely not in the centre.
================== Update: FOUND SOLUTION: I have to turn off autoresizing constraints after creating indicator and then all solutions that where given work:
[activityIndicator setTranslatesAutoresizingMaskIntoConstraints:NO];
I found it on the link given by @Vignesh, so I accept his/her answer.
The four following Swift 5 / iOS 12 code samples show how to center a
UIActivityIndicatorView
inside theUIView
of aUIViewController
with Auto layout.All samples produce the same result but, according to your needs and tastes, you may choose one or the other.
If your
UIActivityIndicatorView
's superview is notself.view
, you simply have to replace eachself.view
call with your own (unwrapped)superview
.1.
NSLayoutConstraint
initializer style2.
UIViewAutoresizing
styleSprings and Struts will be translated into corresponding auto layout constraints at runtime.
3. Visual Format Language style
4.
NSLayoutAnchor
style (requires iOS 9)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:
And to center vertically do this too:
Alternatively, I highly recommend using the FLKAutoLayout project to simplify all this:
https://github.com/dkduck/FLKAutoLayout
Then you can do:
Which is nice :)
You can try this,
Taken from here.
I centered my activity indicator in its superview by adding it in Interface Builder with an alpha of zero (and an IBOutlet for it in my view controller class). Then I added constraints to center it in the X and Y axes. Finally, I added width and height constraints to it to silence an autolayout error.
In my view controller's startActivityIndicator method, I set the alpha of the activity indicator to one and call the startAnimating method on it. In my stopActivityIndicator method, I call the stopAnimating method on it and set the alpha of the activity indicator back to zero.