1

I have a scrollView where I add some UIButtons and UIActivityIndicators in the main thread. Then I perform a [NSThread detachSelectorInBackground:@selector(getImages) toTarget:self withObject:nil];

getImages downloads some images and add them into UIImageViews and then adds the UIImageViews to the scrollView, but they wont show up until the method getImages is done. Is there any way to get the scrollView to redraw or refresh or something like that?

AND If I scroll the scrollView (with my fingers..) during the getImages method, the UIImageViews that has been added shows up.

- (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];
}
4

1 回答 1

1

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

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

于 2010-12-21T13:21:50.863 回答