2016-02-19 56 views
-2

即時通訊嘗試從網絡載入一組圖像並將其顯示在屏幕上的集合視圖中。下面是我的代碼無法使用objectAtIndex屬性

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; 
    cell.layer.cornerRadius = 5; 
    NSURL *url = [NSURL URLWithString: 
        @"http://elatewiki.org/images/thumb/Google.png/120px-Google.png"]; 
    UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 

    UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100]; 

    //recipeImageView.image = [UIImage imageNamed:[recipePhotos objectAtIndex:indexPath.row] ]; 
    recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[0] ]]; 
    return cell; 
} 

,但我不得不使用objectAtIndex:indexPath.row屬性與imageWithData沿着這樣的圖像可以刷卡。有什麼辦法通過我可以使用objectAtIndex:indexPath.row以及NSData dataWithContentsOfURL

+1

凡被定義'recipePhotos'和'recipPhotosUrl'? – Larme

+0

recipePhotos包含靜態圖像文件的名稱 –

+0

recipePhotoUrl包含動態獲取照片的所有URL。 –

回答

1

您可以使用此:

NSString *url_str = [NSString stringWithFormat: @"%@",[recipPhotoUrl objectAtIndex: indexPath.item]]; 
NSURL *url = [NSURL urlWithString:url_str]; 
recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 
+0

它的作品就像一個魅力...謝謝你兄弟! :) –

0

UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 應該放在一個通用的函數中。例如 - (void)viewDidLoad,爲圖像添加一個屬性引用。

recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[0]]];

變化

recipeImageView.image = self.image;

+0

這不是很有幫助。他問如何從數組中的動態url中獲取圖像。這是在主線程... –

2

有什麼呢?

NSURL *url = [NSURL URLWithString: 
       @"http://elatewiki.org/images/thumb/Google.png/120px-Google.png"]; 
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 

反正你接近的解決方案....

if (recipPhotoUrl.count > indexPath.row) 
{ 
    recipeImageView.image = [UIImage imageWithData: [NSData dataWithContentsOfURL:recipPhotoUrl[indexPath.row]]]; 
} 

但儘管如此,你在main thread做這個業務,你,可以肯定,阻止用戶界面,滾動不會順利。 它也不是那麼肯定,因爲你正在訪問索引而不檢查數組是否有足夠的維度。

+0

當我這樣做的應用程序崩潰。如何在工作線程上運行這個? –

+0

當我使用dispatchqueue時,應用程序仍然崩潰 –

+0

您是否檢查數組是否具有正確的維度? –