Search code examples
objective-cmacoscocoansstatusitemnsprogressindicator

Using an NSProgressIndicator in an NSStatusItem


I'm using this code (inspired by an other question on here) :

- (void)showProgressIndicator {

    if (statusItem) {

        NSLog(@"wassup");
        NSView *progressIndicatorHolder = [[NSView alloc] init];
        NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] init];
        [progressIndicator setBezeled: NO];
        [progressIndicator setStyle: NSProgressIndicatorSpinningStyle];
        [progressIndicator setControlSize: NSSmallControlSize];
        [progressIndicator sizeToFit];
        [progressIndicator setUsesThreadedAnimation:YES];
        [progressIndicatorHolder addSubview:progressIndicator];
        [progressIndicator startAnimation:self];
        [statusItem setView:progressIndicatorHolder];
        [progressIndicator setNextResponder:progressIndicatorHolder];
        [progressIndicatorHolder setNextResponder:statusItem];
    }
}

Unfortunately, as soon as this code runs the status item (which is initially showing an image) disappears... Why doesn't my code work?


Solution

  • You probably need to explicitly set the frame on progressIndicatorHolder then center progressIndicator within its superview, e.g.:

    CGRect holderRect = progressIndicatorHolder.bounds;
    CGRect indicatorRect = progressIndicatorHolder.frame;
    indicatorRect.origin.x = (holderRect.size.width - indicatorRect.size.width)/2.0f;
    indicatorRect.origin.y = (holderRect.size.height - indicatorRect.size.height)/2.0f;
    progressIndicator.frame = indicatorRect;
    

    As an alternative, if you find that you want to do more sophisticated layout, you could load the NSStatusItem's view from a nib.