在UIScrollView中加载图像时的活动指示器

时间:2012-04-27 03:02:14

标签: cocoa-touch uiscrollview image-loading

我有UIScrollView,其中包含来自服务器的图像。

我应该在图片当前加载时放置活动指示器。

UIScrollView包含来自服务器的动态图像数量。

我可以知道如何在加载图像时在每个页面上添加活动指示符,并在加载图像后删除。

这是我检索图片的代码:

NSDictionary *items = [NSDictionary dictionaryWithObject:dictInfo forKey:@"images"];
imageList = [items objectForKey:@"images"];
NSArray *img = [imageList objectForKey:@"list"];
NSInteger imgCount = [img count];
buttonArray = [[NSMutableArray alloc] init];

for (int i=0; i<imgCount; i++) {
    NSDictionary *imgDict = [img objectAtIndex:i];
    // REQUEST FOR IMAGES
    NSString *imgPath = [imgDict objectForKey:@"image_slot"];
    NSString *imgURL = imgPath;

    __block ASIHTTPRequest *requestImage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imgURL]];
    [requestImage setCompletionBlock:^{
        imgView = [UIImage imageWithData:[requestImage responseData]];

        if (imgURL.length) {
            [pendingRequests removeObjectForKey:imgURL];
        }

        scrollView.userInteractionEnabled = YES;
        scrollView.exclusiveTouch = YES;
        scrollView.canCancelContentTouches = YES;
        scrollView.delaysContentTouches = YES;
        scrollView.bounces = NO;

        CGRect frame;
        frame.origin.x = self.scrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.size = self.scrollView.frame.size;

        SWTUIButton *imgBtn = [[SWTUIButton alloc] initWithFrame:frame];
        imgBtn.url = [requestImage.userInfo objectForKey:@"rURL"];
        [imgBtn setImage:imgView forState:UIControlStateNormal];
        imgBtn.backgroundColor = [UIColor clearColor];
        [imgBtn addTarget:self action:@selector(buttonpushed:) forControlEvents:UIControlEventTouchUpInside];
        [scrollView addSubview:imgBtn];

        [buttonArray addObject:imgBtn];

        [imgBtn release];

        self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * img.count, self.scrollView.frame.size.height);
    }];

1 个答案:

答案 0 :(得分:1)

我强烈建议您使用https://github.com/jverkoey/nimbus项目中的NINetworkImageView。 它非常轻巧有用。 它有一个委托方法,可以在加载图像时通知您。 你基本上需要做的是: 1.为每个页面创建一个NINetworkImageView,就像使用UIImageView一样,并调用set

  NINetworkImageView* networkImageView = [[[NINetworkImageView alloc] initWithImage:initialImage]
                                      autorelease];
  networkImageView.delegate = self;
  networkImageView.contentMode = UIViewContentModeCenter;
[networkImageView setPathToNetworkImage:
     @"http://farm3.static.flickr.com/2484/3929945380_deef6f4962_z.jpg"
                             forDisplaySize: CGSizeMake(kImageDimensions, kImageDimensions)];

https://github.com/jverkoey/nimbus/tree/master/examples/photos/NetworkPhotoAlbums

  1. 将指示符添加到networkImageView作为子视图。
  2. 按如下方式实施委托:

    - (void)networkImageView:(NINetworkImageView *)imageView didLoadImage:(UIImage *)image {     [imageView removeAllSubviews];

    }

  3. 最终结果将是用于执行相同操作的小得多的代码。