Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center UIActivityIndicatorView in a UIImageView

I've created a custom subclass of UIImageView and in one method I want to add an activity indicator to the center while the image is loading. I'm using the following code, but the activity monitor is positioned well outside of the UIImageView. What can I do to center it exactly within the bounds of the UIImageView?

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

indicator.autoresizingMask =
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleBottomMargin |
UIViewAutoresizingFlexibleLeftMargin;

indicator.center = self.center;

[self addSubview:indicator];    
[indicator startAnimating];
like image 997
Wasim Avatar asked May 28 '12 08:05

Wasim


3 Answers

center property is view's coordinates in coordinate space of its superview. So you need to set coordinates of your indicator in the coordinate space of imageView. Correct way will be:

indicator.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
like image 95
Vladimir Avatar answered Oct 10 '22 04:10

Vladimir


indicator.center = [self convertPoint:self.center fromView:[self superview]];

You only need to convert point because of this (UIView Class Reference):

@property(nonatomic) CGPoint center Discussion

The center is specified within the coordinate system of its superview and is measured in points.

like image 35
Oleg Trakhman Avatar answered Oct 10 '22 03:10

Oleg Trakhman


indicator.center = imageView.center;

like image 2
Fran Sevillano Avatar answered Oct 10 '22 03:10

Fran Sevillano