Search code examples
iosobjective-ccalayercenteringuiactivityindicatorview

Centering Activity Indicator view on its layer


I have not been able to solve this problem searching on the net. I have an Activity indicator view with a layer I would like to customize. More specifically I want to increase its size. The problem is that the activity indicator is not centered anymore on its background.

It should be something rather simple but I cannot figure out how to do it. Managing the layer seems more concise than adding an other subview.

Here is what I get with the code below.

background layer is centered but not the activity indicator

UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]
                                             initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [activityView setColor:[UIColor whiteColor]];
    activityView.layer.frame = CGRectMake(self.view.bounds.size.width/2-30, self.view.bounds.size.height/2-30, 60, 60);
    activityView.layer.cornerRadius = 5;
    [activityView.layer setBackgroundColor:[[UIColor colorWithRed:2/255.0 green:79/255.0 blue:105/255.0 alpha:0.9] CGColor]];

    activityView.center = self.view.center;
    //activityView.center = also tried to center on layer, layer.contentsRect,... without any success;
    [activityView startAnimating];
    [self.view addSubview:activityView];

If anyone could help me...


Solution

  • You can use this to centering activity:

    activityView.subviews[0].center = CGPointMake(CGRectGetMidX(activityView.bounds), CGRectGetMidY(activityView.bounds));
    

    But I think it's bad way. Try to make view and add Activity to this view without change its frame.