Search code examples
objective-capiios8mbprogresshud

MBProgressHUD not working with category


I have created one category class. As my application is working mostly on API calls. So I have used MBProgressHUD to show loading indicator while my API is loading.

-(void)loading {
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.color = [UIColor colorWithRed:79.0/255.0 green:79.0/255.0 blue:79.0/255.0 alpha:1.0];
    [HUD show:YES];
}

and On result I have written,

[HUD hide:YES];

But, I need to write above code in each and every file. So I thought category is the best way to reduce code repetition. If I put loading method in category then simply I call it with

[self loading];

On result my HUD is not hiding. I know there is conflict in HUD creation. Because the HUD which is created in category file is differ from where I am trying to Hide it. I don't know how to handle it.

I have used category for very first time so not have deep knowledge about it.

Can anyone help me out here? Thanks in advance!


Solution

  • Create a Custom class (NSObject subclass) with a Class Method with an argument of UIView described as below.

    Below are two methods (in a new custom class for ProgressHUD) which will be helpful to you to use MBProgressHUD in UIViewController category.

    +(void)showLoading:(UIView *)onView
    {
        HUD = [[MBProgressHUD alloc] initWithView:onView];
        [onView addSubview:HUD];
        HUD.color = [UIColor colorWithRed:79.0/255.0 green:79.0/255.0 blue:79.0/255.0 alpha:1.0];
        [HUD show:YES];
    }
    
    +(void)hideView
    {
        [HUD hide:YES];
    }
    

    Now create a UIViewController category in which below will be two methods only. These methods will be helpful to show the progress hud in your view controller using category.

    UIViewController category methods.

    -(void)showProgressHUD
    {
        [MBProgressHUDCustom showLoading:self.view];
    }
    
    -(void)hideProgressHUD
    {
        [MBProgressHUDCustom hideView];
    }
    

    Please try with above way. Hope this helps. Good Luck!!!