在后台线程中将UIImageView添加到UIScrollView,直到添加完所有内容才会显示

时间:2010-12-21 13:07:44

标签: iphone uiscrollview uiimageview redraw

我有一个scrollView,我在主线程中添加了一些UIButtons和UIActivityIndi​​cators。 然后我执行[NSThread detachSelectorInBackground:@selector(getImages)toTarget:self withObject:nil];

getImages下载一些图像并将它们添加到UIImageViews然后将UIImageViews添加到scrollView,但它们不会出现,直到方法getImages完成。 有没有办法让scrollView重绘或刷新或类似的东西?

和 如果我在getImages方法中滚动scrollView(用我的手指..),则显示已添加的UIImageViews。

- (void) getImages {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int x=5;
    int y=0;
    NSData *imgData;
    UIImage *img;
    UIImageView *imgView;
    for (NSDictionary *tmp in thumbs) {

  imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[Functions urlForFile:[tmp objectForKey:@"img"]]]];
  if ([imgData length] > 0) {
    img = [[UIImage alloc] initWithData:imgData];
    imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y + (133-img.size.height)/2, 100, img.size.height)];

    imgView.image = img;
    [imgView setAlpha:0.0];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] setAlpha:1.0];
    [self.scrollView addSubview:imgView];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:2.0];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] setAlpha:0.0];
    [imgView setAlpha:1.0];
    [UIView commitAnimations];
    [[self.scrollView viewWithTag:1500000*[[tmp objectForKey:@"id"] intValue]] removeFromSuperview];      

    [imgView release];
    [img release];
    [imgData release];

    x+=105;
    if (x > 300) {
      x=5;
      y+=138;
    }
  }
}
[pool release];
[appDelegate.loadingView setHidden:YES];
}

1 个答案:

答案 0 :(得分:1)

在后台更改UI不是线程安全的!在后台下载但不显示。要逐个显示图片,您可以尝试使用performSelectorOnMainThread:@selector() withObject:nil waitUntilDone:YES运行图片 例如self.scrollView addSubview:

但是,UI应该始终使用MainThread(例如动画)