13

我正在使用 AFNetworking 库来设置带有 URL 内容的图像。在以下示例中,topLeftImage 是 UIImageView 的一个实例。

[topLeftImage setImageWithURL:[NSURL URLWithString:imageURL]];

我想做的是在图像下载时显示 UIActivityIndi​​catorView 。但是我不知道在哪里触发活动指示器的启动和停止。以下是我的活动指示器代码。

UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[topLeftImage addSubview:activityIndicator];
[activityIndicator startAnimating];

如何将上述代码链接到 setImageWithURL 方法,以便仅在图像下载时显示活动指示器?

4

2 回答 2

38

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, NSHTTPURLResponse *response, NSError *error)
 {
     [_activityIndicator setHidden:YES];
     [_activityIndicator stopAnimating];
 }];
于 2013-02-04T18:55:24.473 回答
2

在 Swift 中很extension简单:UIImageView

extension UIImageView {

    func setImageWithString(string: String?) {

        if let string = string, let url = NSURL(string: string) {

            let activityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame)))
            activityIndicatorView.hidden = false
            activityIndicatorView.color = UIColor.lightGrayColor()

            addSubview(activityIndicatorView)
            bringSubviewToFront(activityIndicatorView)

            activityIndicatorView.startAnimating()

            setImageWithURLRequest(NSURLRequest(URL: url), placeholderImage: nil, success: { request, response, image in

                self.image = image
                activityIndicatorView.hidden = true
                activityIndicatorView.stopAnimating()
                activityIndicatorView.removeFromSuperview()

                }, failure: { request, response, error in

                    activityIndicatorView.hidden = true
                    activityIndicatorView.stopAnimating()
                    activityIndicatorView.removeFromSuperview()
            })
        }
    }
}
于 2016-02-14T07:45:28.653 回答