我正在使用AFNetworking库来设置URL的内容.在以下示例中,topLeft
Image是UI
ImageView的一个实例.
[topLeftImage setImageWithURL:[NSURL URLWithString:imageURL]];
我想做的是在图像下载时显示一个UIActivityIndicatorView.但是,我无法确定触发活动指示器的启动和停止的位置.以下是我的活动指标代码.
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; [topLeftImage addSubview:activityIndicator]; [activityIndicator startAnimating];
解决方法
UIImageView AFNetworking.h类别提供了一个setImageWithURL方法,允许您使用成功和失败的块.一旦请求完成成功或失败,该块将被执行.所以你可以在请求之前启动动画并将其停止在成功和失败的块.这是一个示例代码:
NSURL *imageURL = [NSURL URLWithString:@"http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/402px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg"]; NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageURL]; [_activityIndicator setHidden:NO]; [_activityIndicator startAnimating]; [_imageView setImageWithURLRequest:imageRequest placeholderImage:nil success:^(NSURLRequest *request,NSHTTPURLResponse *response,UIImage *image) { [_activityIndicator setHidden:YES]; [_activityIndicator stopAnimating]; _imageView.image = image; } failure:^(NSURLRequest *request,NSError *error) { [_activityIndicator setHidden:YES]; [_activityIndicator stopAnimating]; }];