在UIImageView中居中显示UIActivityIndicatorView

5

我创建了一个自定义的UIImageView子类,在其中一个方法中,当图像正在加载时,我想在中心位置添加一个活动指示器。我使用以下代码,但是活动监视器的位置远离UIImageView。我该怎么做才能确切地将其居中在UIImageView的边界内?

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

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

indicator.center = self.center;

[self addSubview:indicator];    
[indicator startAnimating];
3个回答

15

center 属性是视图在其父视图的坐标空间中的坐标。因此,您需要将指示器的坐标设置在imageView的坐标空间中。正确的方法如下:

indicator.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));

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

只有因为这个原因,你需要转换点(UIView Class Reference):

@property(nonatomic) CGPoint center Discussion

中心点是在其父视图的坐标系内指定的,以点为单位测量。


2

indicator.center = imageView.center;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接