开发者

How to add Activity Indicator as subview to UIButton?

Can we add activity indicator as subview to UIButton?

If yes then p开发者_运维技巧lz tell me how to do that?

I used [button addSubview:activityIndicator];

Not working...


I found that adding a UIActivityIndicatorView to a UIButton was a really useful method to allow users to know something is happening without having to use the MBProgressHUD (I think the HUD is really good but should not be used in all situations.

For this reason I created two functions:

I have already allocated my UIButton so it is a class variable called _confirmChangesButton I then create my activity indicator, set its frame (taking into account the button size) and then adding the indicator is easy.

- (void)addActivityIndicatorToConfirmButton {

    // Indicator needs to be in the middle of the button. So half the screen less half the buttons left inset less half the activity indicator size
    CGRect rect = CGRectMake([UIScreen mainScreen].bounds.size.width/2 - 10 - 15, 5, 30, 30);

    UIActivityIndicatorView * activity = [[UIActivityIndicatorView alloc] initWithFrame:rect];
    activity.hidesWhenStopped = YES;

    [_confirmChangesButton setTitle:@"" forState:UIControlStateNormal];
    [_confirmChangesButton addSubview:activity];
    [activity startAnimating];
}

Having a removal function is also useful if you are using blocks. It might be that the completion task comes back with a failure and so we want to remove the indicator and change the title back. In this function we need to make sure to remove the indicator and not the button label which is the other subview on this button.

- (void)removeActivityIndicatorFromConfirmButton {

    UIActivityIndicatorView * activity = _confirmChangesButton.subviews.lastObject;;

    [activity removeFromSuperview];

    [_confirmChangesButton setTitle:@"Confirm Change" forState:UIControlStateNormal];
}

I found that using these two you can create a much better user experience letting the user know what is going on when they press buttons.

Hope this helps


Use the below code below to add acitivity indicator a button or any uiview object

UIActivityIndicatorView *aView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
aView.frame = CGRectMake(0, 0, {yourButton}.frame.size.width, {yourButton}.frame.size.height);
aView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
[{yourButton} addSubview:aView];
[aView startAnimating];

Hope this will help..


I don't think it's possible to add a view to a button. UIButton have this method because it's inherited from UIVIew. The real question is : why do you want to add an activity indicator on a button and not elsewhere ?


did you do [activityIndicator startAnimating]; ALso as u are using it in a tableview just check if the tags are set properly

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜