Is there a way to have the UIActivityIndicatorView display in the center of the screen to mirror the NetworkActivityIndicator? So I want the same process as the NetworkActivityIndicator, just with a larger indicator that will be more noticeable to the user.
Try this:
UIView *view = /* whatever your main view is */
UIActivityIndicatorView *spinner = [[UIActivityIndicatorVIew alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
CGRect frame = spinner.frame;
frame.origin.x = view.frame.size.width / 2 - frame.size.width / 2;
frame.origin.y = view.frame.size.height / 2 - frame.size.height / 2;
spinner.frame = frame;
[view addSubview:spinner];
[spinner startAnimating];
[spinner release]; // Or, you could keep a handle to this for later to stop animating it
This basically centers the spinner in its enclosing view, whatever that might be.
If you do not keep a handle to spinner, and if spinner is the only subview of view (or at least in a well known position), you could later get a handle to it by dipping into [view subviews]
for it.
EDIT: You could also probably use CGRectGetMidX()
and CGRectGetMidY()
instead of the more complicated equations above for finding x
and y
... Your mileage may vary. :-)
EDIT (2/25/2016)
This answer has received some up-votes recently, so I thought an update was in order. There is actually an even better way to do this now. This example places a UIActivityIndicatorView
in the center of a UITableView
.
self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
_spinner.translatesAutoresizingMaskIntoConstraints = NO;
_spinner.hidesWhenStopped = YES;
[self.tableView addSubview:self.spinner];
[self.tableView addConstraints:@[
[NSLayoutConstraint constraintWithItem:_spinner
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.tableView
attribute:NSLayoutAttributeCenterX
multiplier:1 constant:0],
[NSLayoutConstraint constraintWithItem:_spinner
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.tableView
attribute:NSLayoutAttributeCenterY
multiplier:1 constant:0]
]];
This works for me inside a UIViewController:
override func viewDidLayoutSubviews() {
activityIndicator.center = view.center
}
indicatorView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
indicatorView.center = self.view.center;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With