2014-02-06 200 views
0

我有一個代碼來顯示來自遠程URL的圖像。如何顯示UIImageView的加載圖像

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     NSData *imageData = nil; 

     imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:image]]; 

     if (imageData){ 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       // UIKit, which includes UIImage warns about not being thread safe 
       // So we switch to main thread to instantiate image 
       UIImage *image1 = [UIImage imageWithData:imageData]; 
       self.imageLabel.image = image1; 


      }); 
     } 
    }); 

但下載圖像需要2秒。我試圖把動畫加載圖像到UIImageView,但沒有奏效。我如何在2秒內實現加載圖像?

回答

2

通常iOS中沒有提供佔位符圖像的內置方法。您可以使用名爲SDWebImage.framework的框架完成此任務。在我的一個項目中,我必須顯示佔位符圖像,同時從服務器加載主圖像。我使用了相同的框架並使用UICollectionView顯示圖像,我使用的代碼是:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView 
      cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CollectionCell *Cell = [collectionView 
          dequeueReusableCellWithReuseIdentifier:@"MyCell" 
          forIndexPath:indexPath]; 



    [Cell.imageview setImageWithURL:url placeholderImage:[UIImage imageNamed:@"image.png"]]; 

    return myCell; 
} 
相關問題