Karuppu MGR Karuppu MGR - 6 months ago 20
iOS Question

Centring a view at the centre of view controller

I'm trying to show an animated spinner while loading a table view.

loadingView = [[UIView alloc] initWithFrame:CGRectMake(75, 155, 170, 170)];
loadingView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
loadingView.clipsToBounds = YES;
loadingView.layer.cornerRadius = 10.0;

activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityView.frame = CGRectMake(65, 40, activityView.bounds.size.width, activityView.bounds.size.height);
[loadingView addSubview:activityView];

loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 115, 130, 22)];
loadingLabel.backgroundColor = [UIColor clearColor];
loadingLabel.textColor = [UIColor whiteColor];
loadingLabel.adjustsFontSizeToFitWidth = YES;
loadingLabel.textAlignment = NSTextAlignmentCenter;
loadingLabel.text = @"Loading...";
[loadingView addSubview:loadingLabel];

[self.view addSubview:loadingView];
[activityView startAnimating];


I have embedded a
UIActivityIndicatorView
within
loadingView
.
The problem that I'm facing is:


  1. The loading view is not at the centre of view controller.

  2. I'm trying to centre the loading view to the centre of view controller and the
    UIActivityIndicatorView
    has to be in the centre of loading view but it's not getting centred like the way I'm expecting.


Answer

In ViewDidLoad add this code it works:

[self.view addSubview: loadingView];
loadingView .center = CGPointMake(CGRectGetWidth(self.view.frame) / 2, CGRectGetHeight(self.view.frame) / 2);
Comments