简体   繁体   中英

Custom UIView in storyboard not showing subviews

I have created a custom UIView to show an UIActivityIndicatorView and a message. Idea is to reuse this across my app for consistency. Below is the code:

@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];
    }
}

To try this out, I added a UIView to one of my views in the storyboard and set the class for that view to CDActivityIndicator. When I call begin() from the corresponding View Controller, the CDActivityIndicator gets shown as an empty view with the expected background color. However, the activity indicator doesn't show. All methods are getting called as expected.

Any idea what I might be missing? Thanks!

You should change your subviews frame setting like this.

CGPoint point = [self.superview convertPoint:self.center toView:self];
[activityIndicator setCenter:point];
[message setFrame:self.bounds];

The frame defines the origin and dimensions of the view in the coordinate system of its superview. Every UIView has its own coordinate system. You should take this into account.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM