如何以编程方式使用活动指示符进行叠加

时间:2016-08-13 07:48:14

标签: ios objective-c uiactivityindicatorview

我需要在目标c中设置带有模糊叠加背景的活动指示器。如何做到这一点。

我尝试了这段代码,但无法为view设置叠加层。注意我只有一个按钮的视图控制器。按下该按钮后我需要用活动指示器进行叠加。

 spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(150, 225, 20, 30)];
    [spinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    spinner.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
    spinner.color = [UIColor redColor];
    [self.view addSubview:spinner];

怎么做?

1 个答案:

答案 0 :(得分:0)

这是我长期以来在我的一个项目中所做的。 :)

视图标记:

#define TAG_BGVIEW 182


/*
 *********************************************************
 This method creates the activity alert on the view and
 sets its center to the center of the specified view
 *********************************************************
 */
+ (void)showActivityIndicatorOnView:(UIView*)view withCenter:(CGRect)frame withText:(NSString*)text {

    [view setUserInteractionEnabled:NO];


    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(10, frame.size.height / 2 -70, 300, 170)];
    backgroundView.tag = TAG_BGVIEW;
    [backgroundView.layer setCornerRadius:5.0f];
    [backgroundView.layer setBorderWidth:2.0f];
    [backgroundView.layer setBorderColor:[UIColor blackColor].CGColor];
    [backgroundView setBackgroundColor:[UIColor blackColor]];
    [backgroundView setAlpha:0.8f];

    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    [spinner startAnimating];
    spinner.center = CGPointMake(backgroundView.frame.size.width / 2, backgroundView.frame.size.height / 2);


    UILabel *indicatorLabel = [[UILabel alloc]initWithFrame:CGRectMake(frame.size.width / 2, frame.size.height / 2 + spinner.frame.size.height + 15, 300, 40)];
    [indicatorLabel setText:text];
    [indicatorLabel setTextAlignment:NSTextAlignmentCenter];
    [indicatorLabel setNumberOfLines:0];
    [indicatorLabel setFont:[AppStyle getTableViewCellFont]];
    [indicatorLabel setTextColor:[UIColor whiteColor]];
    indicatorLabel.center  = CGPointMake(backgroundView.frame.size.width / 2, backgroundView.frame.size.height / 2 + spinner.frame.size.height + 10);

    [view addSubview:backgroundView];
    [backgroundView addSubview:spinner];
    [backgroundView addSubview:indicatorLabel];
}

这是你如何阻止它:

/*
 *********************************************************
 This method stops the activity indicator visible on
 the screen
 *********************************************************
 */
+ (void)stopActivityIndicatorOnView:(UIView*)view {

    for (UIView *currentView in view.subviews) {


        if ([currentView isKindOfClass:[UIView class]]) {

            UIView *view = (UIView*)currentView;

            if (view.tag == TAG_BGVIEW) {
                [view removeFromSuperview];
            }

        }

    }

    [view setUserInteractionEnabled:YES];
}