2011-01-13 60 views
2

我正在使用帶有兩個按鈕名稱的簡單警報視圖,取消。如何將活動指標放置在警報視圖中,當點擊該警報視圖的按鈕時

當我按下確定,取消警報視圖退出一般。

但我需要時,我點擊警報視圖確定按鈕與退出警報視圖活動指標 將在同一警報視圖上運行2分鐘並退出。當我點擊取消它正常退出。

任何人都可以幫助我。

謝謝你提前。

+0

爲什麼需要這樣做?警報視圖消失後,顯示等待視圖一段時間。 – xhan 2011-01-13 08:14:19

回答

3

您可以修改「確定」按鈕的UI控件事件,以便爲該按鈕調用您自己的事件處理程序,並且在長時間運行任務完成之前警報視圖不會被解除。 在該事件處理程序中,將活動指示器附加到視圖並使用GCD異步啓動您的任務。

#import <dispatch/dispatch.h> 

// ... 

UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Test" message:@"Message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK" ,nil]; 

for (UIView *subview in alert.subviews) 
{ 
    if ([subview isKindOfClass:[UIControl class]] && subview.tag == 2) { 
     UIControl* button = (UIControl*) subview; 
     [button addTarget:self action:@selector(buttonOKPressed:) forControlEvents:UIControlEventTouchUpInside]; 
     [button removeTarget:alert action:nil forControlEvents:UIControlEventAllEvents]; 
    } 
} 
[alert show]; 
[alert release]; 

// ... 

-(void) buttonOKPressed:(UIControl*) sender { 

    [sender removeTarget:self action:nil forControlEvents:UIControlEventAllEvents]; 
    UIAlertView* alert = (UIAlertView*)[sender superview]; 
    CGRect alertFrame = alert.frame; 
    UIActivityIndicatorView* activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; 
    activityIndicator.frame = CGRectMake(0,alertFrame.size.height, alertFrame.size.width,30); 
    activityIndicator.hidden = NO; 
    activityIndicator.alpha = 0.0; 
    activityIndicator.contentMode = UIViewContentModeCenter; 
    [activityIndicator startAnimating]; 
    [alert addSubview:activityIndicator]; 
    [activityIndicator release]; 
    [UIView animateWithDuration:0.3 animations:^{ 
     alert.frame = CGRectMake(alertFrame.origin.x, alertFrame.origin.y, alertFrame.size.width, alertFrame.size.height+50); 
     activityIndicator.alpha = 1.0; 

    }];   
    //alert.userInteractionEnabled = NO; // uncomment this, if you want to disable all buttons (cancel button) 
    dispatch_async(dispatch_get_global_queue(0,0), ^{ 
     [NSThread sleepForTimeInterval:5]; // replace this with your long-running task 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      if (alert && alert.visible) { 
       [alert dismissWithClickedButtonIndex:alert.firstOtherButtonIndex animated:YES]; 
      } 
     }); 
    }); 
}