2012-06-27 42 views
0

我有這種方法我用來加載許多圖像滾動視圖,但是當圖像加載從url我的滾動視圖卡住,我不明白如何加載他們在後臺,所以用戶不會感覺到它。如何從後臺加載許多照片url(異步)

該方法將在「for」循環中調用幾次(8)。

- (void)loadPhotosToLeftscroll{ 

    //getting image information from JSON 
    NSMutableDictionary *photoDict; 
    photoDict = [leftPhotoArray lastObject]; 

    //getting the photo 
    NSString *photoPath = [photoDict objectForKey:@"photos_path"]; 
    NSLog(@"photo Path:%@",photoPath); 


    NSData * imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:photoPath]];  

      UIImage *image = [UIImage imageWithData:imageData]; 
      // use the image how you like, say, as your button background 

      //calculating the hight of next photo 
      UIImageView *leftImage = [leftBlockScroll.subviews lastObject]; 

      //allocating photoView 
      UIImageView *photoView = [[UIImageView alloc]initWithFrame:CGRectMake(5 , leftImage.frame.origin.y + leftImage.frame.size.height+5, image.size.width/2, image.size.height/2)]; 
      photoView.userInteractionEnabled=YES; 
      [photoView.layer setMasksToBounds:YES]; 
      [photoView.layer setCornerRadius:3]; 


      //getting items list 
      NSDictionary *sh_items = [photoDict objectForKey:@"items"]; 

      //adding image button 
      UIButton *imageOverButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
      imageOverButton.frame = CGRectMake(0, 0, photoView.frame.size.width, photoView.frame.size.height); 
      [imageOverButton addTarget:self action:@selector(LeftimagePressed:) forControlEvents:UIControlEventTouchUpInside]; 
      [imageOverButton setTag:[leftPhotoArray count]-1]; 
      [photoView addSubview:imageOverButton]; 

      //adding sh button to imageView 
      [self addThe_sh_signs:sh_items To_ImageView:photoView]; 

      //subViewing the image to the scrollView 
      [self insert_Image:image toImageView:photoView in_Scroll:leftBlockScroll]; 

      //calclulating the position of next imageView in scroll. 
      nextLeftPhotoHight = photoView.frame.size.height + photoView.frame.origin.y + 5; 

      //calculating the hight of the highest scroll view in both. 
      leftBlockScroll.contentSize = CGSizeMake(160, [self theSizeOfScrollViewHight]); 
      rightBlocScroll.contentSize = CGSizeMake(160, [self theSizeOfScrollViewHight]); 
      isLoadindContant = NO; 
      [self.view reloadInputViews]; 
      [leftBlockScroll reloadInputViews]; 

} 

請不要給我發一些鏈接,試圖解釋如何使用異步的。 嘗試按照您在此處看到的方法進行解釋。 我在這裏的任何問題,你需要問我來幫助我。

+0

我很確定你這樣做的方式解釋「前景」加載。 – Dustin

回答

2

您必須以正確的方式異步執行此操作。我不認爲有任何解決辦法。我創建了一個UIImageView對象的子類,並將它的許多實例放在一個talbe的單元格中(在你的情況下在滾動視圖中)。子類對象使用url初始化並異步加載它們的圖像(使用一些緩存,以便圖像不會每次加載)。

本教程幫了我很大的開頭: http://www.markj.net/iphone-asynchronous-table-image/

你將不得不採取,爲您的滾動視圖。下層原則保持不變。