我想在单击UIButton时添加一个activityindicator并继续设置动画,直到来自服务url的数据加载为止。如果它加载则会移动到下一个视图。但是我无法这样做..
这是我的代码..
-(IBAction)switchtoGetProviders
{
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(225, 115, 30, 30)];
[activity setBackgroundColor:[UIColor clearColor]];
[activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:activity];
[activity release];
[activity startAnimating];
NSURL *urlString= [NSString stringWithFormat:@"http://www.something.net/service.svc/Xml"];
if(arr.count>0)
{
[activity stopAnimating];
ViewController2 *gp=[ViewController2 alloc];
[self presentModalViewController:gp animated:NO];
[gp release];
}
else
{
UIAlertView *alert = [[[UIAlertView alloc]initWithTitle: @"Results not found"
message: @""
delegate: self
cancelButtonTitle:@"OK"
otherButtonTitles:nil]autorelease];
[alert show];
}
}
实际上,当arr为null时,我会得到一个alertView
。当alertView
出现时activityindicator
正在启动。当我点击alertView
的确定按钮时,它会停止制作动画。但是我希望它在触摸UIbutton
时立即启动。我该怎么做 ?
哪里出错?
答案 0 :(得分:1)
在停止制作动画之前不要释放它...如果你发布那么你就失去了对它的引用..
[activity release];//Dont Release here
[activity startAnimating];
[activity stopAnimating];
[activity release];
答案 1 :(得分:0)
您的代码存在多个问题。
首先是发布,这是早期,第二,你没有给UI任何时候添加UIActivityIndicatorView
并让它开始动画。您也忘记了init
您分配的ViewController2
。
我还猜你没有发布所有代码,因为NSURL *urlString= [NSString stringWithFormat:@"http://....
不会创建有效的NSURL
对象。我也很想知道你来自arr
的{{1}}变量。
如果您真的想在一种方法中完成所有操作,则必须使用GCD。
-(IBAction)switchtoGetProviders
{
UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(225, 115, 30, 30)];
[activity setBackgroundColor:[UIColor clearColor]];
[activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:activity];
[activity startAnimating];
int64_t delayInSeconds = 0.1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSURL *urlString= [NSString stringWithFormat:@"http://www.something.net/service.svc/Xml"];
if(arr.count>0) {
[activity stopAnimating];
[activity removeFromSuperview];
[activity release];
ViewController2 *gp= [[ViewController2 alloc] init];
[self presentModalViewController:gp animated:NO];
[gp release];
} else {
UIAlertView *alert = [[[UIAlertView alloc]initWithTitle: @"Results not found" message: @"" delegate: self cancelButtonTitle:@"OK" otherButtonTitles:nil]autorelease];
[alert show];
[alert release];
});
}