我创建了一个自定义UIView来显示UIActivityIndicatorView和一条消息。想法是在我的应用程序中重用它以保持一致性。以下是代码:
@implementation CDActivityIndicator
@synthesize activityIndicator, message;
//init method called when the storyboard wants to instantiate this view
- (id) initWithCoder:(NSCoder*)coder {
if ((self = [super initWithCoder:coder])) {
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
message = [[UILabel alloc] initWithFrame:CGRectZero];
[message setBackgroundColor:[UIColor clearColor]];
[message setTextColor:[UIColor whiteColor]];
[message setTextAlignment:NSTextAlignmentCenter];
[message setFont:[UIFont fontWithName:@"HelveticaNeue" size:15.0f]];
[self addSubview:activityIndicator];
[self addSubview:message];
//set background color
[self setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5]];
}
return self;
}
-(void) layoutSubviews {
[super layoutSubviews];
//position the indicator at the center of the view
[activityIndicator setCenter:[self center]];
//position the label
[message setFrame:[self frame]];
}
- (void) begin {
//make sure the current view is visible, and message is hidden
[self setHidden:NO];
[activityIndicator setHidden:NO];
[self bringSubviewToFront:activityIndicator];
[message setHidden:YES];
[self performSelectorOnMainThread:@selector(startAnimating) withObject:self waitUntilDone:YES];
}
- (void) startAnimating {
if( !activityIndicator.isAnimating ) {
[activityIndicator startAnimating];
}
}
为了尝试这一点,我在故事板中为我的一个视图添加了一个UIView,并将该视图的类设置为CDActivityIndicator。当我从相应的View Controller调用begin()时,CDActivityIndicator将显示为具有预期背景颜色的空视图。但是,活动指示器未显示。所有方法都按预期调用。
知道我可能缺少什么吗?谢谢!
答案 0 :(得分:1)
您应该像这样更改子视图框架设置。
CGPoint point = [self.superview convertPoint:self.center toView:self];
[activityIndicator setCenter:point];
[message setFrame:self.bounds];
框架在其超视图的坐标系中定义视图的原点和尺寸。每个UIView都有自己的坐标系。你应该考虑到这一点。