文章目錄
  1. 1. 首先,需要一個singleton來統管這個HUD,避免一次出現兩個hud以上的窘境
  2. 2. 接著實作兩個 instanceMethod
  3. 3. 兩個class method

首先,需要一個singleton來統管這個HUD,避免一次出現兩個hud以上的窘境

static LoadingView *myInstance = nil;

+(LoadingView *)shared
{
    // check to see if an instance already exists
    if (nil == myInstance) {
        myInstance  = [[[self class] alloc] init];
        // initialize variables here
    }
    // return the instance of this class
    return myInstance;
}

接著實作兩個 instanceMethod

+ (void)dismiss{

    [[UIApplication sharedApplication] endIgnoringInteractionEvents];
    [[self shared] selfHide];
}
+ (void)show
{
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    [[self shared] selfShow];
}

兩個class method

自window中找到hud並移除

-(void)selfHide{
    [[((AppDelegate *)([UIApplication sharedApplication].delegate)).window viewWithTag:56789] removeFromSuperview];
    [[((AppDelegate *)([UIApplication sharedApplication].delegate)).window viewWithTag:56790] removeFromSuperview];
}

將hud加到最上層的window,範例中的hud為中間一個靜置圖片,週遭再放一個不斷旋轉的圖片

-(void)selfShow{

    UIImageView *mView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [mView setImage:[UIImage imageNamed:@"loading.png"]];
    mView.tag = 56789;
    [mView setCenter:((AppDelegate *)([UIApplication sharedApplication].delegate)).window.center];

    UIImageView *mView2 = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 100, 100)];
    [mView2 setImage:[UIImage imageNamed:@"loading2.png"]];
    mView2.tag = 56790;
    [mView2 setCenter:mView.center];

    if ([mView2.layer animationForKey:@"SpinAnimation"] == nil) {
        CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        animation.fromValue = [NSNumber numberWithFloat:0.0f];
        animation.toValue = [NSNumber numberWithFloat: 2*M_PI];
        animation.duration = 1.0f;
        animation.repeatCount = INFINITY;
        [mView2.layer addAnimation:animation forKey:@"SpinAnimation"];
    }

    [((AppDelegate *)([UIApplication sharedApplication].delegate)).window addSubview:mView];
    [((AppDelegate *)([UIApplication sharedApplication].delegate)).window addSubview:mView2];

}

接著,在其他地方引用,再呼叫 [LoadingView show]、[LoadingView dismiss] 就可以了

文章目錄
  1. 1. 首先,需要一個singleton來統管這個HUD,避免一次出現兩個hud以上的窘境
  2. 2. 接著實作兩個 instanceMethod
  3. 3. 兩個class method