Richard Knop
Richard Knop

Reputation: 83755

I am trying to center UIActivityIndicatorView over a UITableView but it has top margin

I am using Xcode 4.2 on Snow Leopard. What I am trying to do. Basically, I have a master view controller with a table view. In order to populate the table view I need to call an API and download the information from there.

While downloading the data from the API, I would like to show an activity indicator in order to let a user know something is happening and the app is not stuck.

What I have done is I have a created a new UIView over the table view with alpha 0.5 and put an activity indicator in its middle. This is the code I execute when the master controller view loads:

// Show the activity indicator
self.overlayView = [[UIView alloc] init];
self.overlayView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
self.overlayView.frame = self.tableView.frame;
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
CGRect frame = self.overlayView.frame;
self.activityIndicator.center = CGPointMake(frame.size.width/2, frame.size.height/2);
[self.overlayView addSubview:self.activityIndicator];
[self.activityIndicator startAnimating];
[self.tableView addSubview:self.overlayView];

When the data is loaded from the API, I hide the overlay view and the activity indicator:

[self.activityIndicator removeFromSuperview];
[self.overlayView removeFromSuperview];

It is working fine but the problem is the overlay view is not aligned properly, it has a top margin and it is not looking good. Here's how it looks:

enter image description here

Upvotes: 3

Views: 5667

Answers (1)

Paul.s
Paul.s

Reputation: 38728

Dont't use

self.overlayView.frame = self.tableView.frame;

instead use

self.overlayView.frame = self.tableView.bounds;

It looks like your tableView has origin.y = 20.0f;


Other notes

  • The designated initializer for UIView is initWithFrame: so you should be using that.

  • You can simply this

      self.activityIndicator.center = CGPointMake(frame.size.width/2, frame.size.height/2);
    

    to

      self.activityIndicator.center = self.overlayView.center;
    

Upvotes: 6

Related Questions