当uitextview使用google api加载当前位置时,如何停止UIActivityIndicatorView。
这是我的代码:
@implementation ViewController
@synthesize loctxt;
- (void)viewDidLoad {
loctxt=[[UITextView alloc]initWithFrame:CGRectMake(10, 50, 220, 30)];
loctxt.backgroundColor=[UIColor whiteColor];
loctxt.delegate=self;
[self.view addSubview:loctxt];
locbtn=[[UIButton alloc]initWithFrame:CGRectMake(240, 50, 40, 30)];
[locbtn addTarget:self action:@selector(clickToGetLocation)forControlEvents:UIControlEventTouchUpInside];
locbtn.backgroundColor=[UIColor grayColor];
[locbtn setImage:[UIImage imageNamed:@"sst14.gif"] forState:UIControlStateNormal];
[self.view addSubview:locbtn];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)clickToGetLocation {
spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0,100, 20, 20)];
[spinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:spinner];
**[spinner startAnimating];**
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv",delegate.latitude, delegate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSLog(@"%@",locationString);
locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
**self.loctxt.text=[locationString substringFromIndex:6];**
//if i use code [spinner stopanimating]; here then the indicator does not appear
}
答案 0 :(得分:3)
问题是您尝试启动微调器,从Internet加载数据,然后在主线程上全部停止微调器,并且所有这些都在同一方法中。在主线程上进行同步网络是BAD。
您需要启动微调器,然后在后台执行网络访问。完成后,然后在主线程上停止微调器。
GCD对此非常好。像这样:
- (void)clickToGetLocation {
spinner = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0,100, 20, 20)];
[spinner setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:spinner];
[spinner startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv",delegate.latitude, delegate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSLog(@"%@",locationString);
locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
dispatch_async(dispatch_get_main_queue(), ^{
self.loctxt.text = [locationString substringFromIndex:6];
[spinner stopAnimating];
});
});
}
答案 1 :(得分:1)
你可以尝试这个spinner.hidesWhenStopped = YES