2010-12-21 40 views
1

我有一個scrollView,我在主線程中添加了一些UIButtons和UIActivityIndi​​cators。 然後我執行一個[NSThread detachSelectorInBackground:@selector(getImages)toTarget:self withObject:nil];將UIImageView添加到後臺線程中的UIScrollView,不會顯示直到全部添加

getImages下載一些圖像並將它們添加到UIImageView中,然後將UIImageView添加到scrollView,但它們不會顯示,直到方法getImages完成。 有什麼辦法讓scrollView重繪或刷新或類似的東西?

AND 如果我在getImages方法中滾動scrollView(用我的手指......),已添加的UIImageView將顯示出來。

- (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

更改背景中的UI不是線程安全的!在後臺下載但不顯示。要逐個顯示圖像,您可以嘗試使用performSelectorOnMainThread:@selector() withObject:nil waitUntilDone:YES (例如self.scrollView addSubview:)運行它。

但同樣,UI應該總是使用MainThread(例如動畫)

+0

好了,工作:) 謝謝! – origon 2010-12-21 13:30:27