我正在使用简单的警报视图,其中两个按钮名称为ok,取消。
当我按下确定时,取消警报视图退出为一般。
但是我需要在点击警报视图确定按钮时退出警报视图活动指示器 将在同一个警报视图上运行2分钟并退出。当我点击取消它正常退出。
任何人都可以帮助我。
提前感谢你。
答案 0 :(得分: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];
}
});
});
}