Add UIActivityIndicatorView into UIBarButton

早过忘川 提交于 2019-12-02 17:57:54
ferdil

If you're trying to show the activity wheel in a navigation bar button (e.g. you might have a refresh button on your navbar) - you can create a new UIBarButtonItem with a custom view being the UIActivityIndicatorView:

Objective-C

uiBusy = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
uiBusy.hidesWhenStopped = YES;
[uiBusy startAnimating];
[self.navigationItem.rightBarButtonItem initWithCustomView:uiBusy];

Swift

let uiBusy = UIActivityIndicatorView(activityIndicatorStyle: .White)
uiBusy.hidesWhenStopped = true
uiBusy.startAnimating()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: uiBusy)

This overwrites your rightBarButtonItem with the spinning wheel. When you're done, just recreate the rightBarButtonItem.

activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityIndicator.hidesWhenStopped = YES;
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];

Place the following where ever is needed:

[activityIndicator startAnimating];
[activityIndicator stopAnimating];

Actually activity indicator is not added as toolbar item. It's a subview of current view.


    UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    [act setCenter:CGPointMake(20, 20)];
    [act startAnimating];
    [self.view addSubview:act];

Remember to release it in -(void)dealloc.

Use this Methods

-(void)startAniatingActivityIndicator{
@try {
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityIndicator.frame = CGRectMake(self.window.frame.size.width-30, 32.5, activityIndicator.bounds.size.width, activityIndicator.bounds.size.height);
    [self.window addSubview:activityIndicator];
    [activityIndicator startAnimating];
    [self.window bringSubviewToFront:activityIndicator];
}
@catch (NSException *exception) {

}
@finally {

}

}

-(void)stopAniatingActivityIndicator{
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
activityIndicator = nil;

}

UIActivityIndicatorView is a type of view. Set its frame to be within your button and use -addSubview to add it to the view hierarchy of the UIBarButton.

I'm oversimplifying, since you have to try to make it fit the space (possibly by scaling) and center it...

pseudocode, i'm not going to check this in Xcode, but something like this should work:

UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] init];
act.frame = CGMakeRect(3,3,25,25);
[myBarButton addSubview:act];
[act release];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!