2017-09-02 54 views
0

我試圖從URL添加圖像到UIImageView。我沒有收到任何錯誤,但屏幕上沒有顯示任何內容。Swift 3將圖像從URL添加到UIImageView

我在這裏做錯了什麼?

我用.xcassets的圖像使用了相同的方法,它工作正常,但它不是從遠程URL工作。

這裏是我的文件:

RelatedCollectionViewCell.swift

class RelatedCollectionViewCell: UICollectionViewCell { 

    @IBOutlet weak var related: UIImageView! 

} 

ViewController.swift

var images = [AnyObject]() 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return images.count 
} 

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

    do { 
     try images.append(UIImage(data: Data(contentsOf: URL(string:"https://i.ytimg.com/vi/kWxHV9jkwSA/hqdefault.jpg")!))!) 
    } catch { 
     print(error) 
    } 

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RelatedCollectionViewCell", for: indexPath) as! RelatedCollectionViewCell 

    cell.related.image = images[indexPath.row] as? UIImage 

    return cell 
} 

回答

0

這不是在那個collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)執行其內部零項的時刻,因爲工作images陣列。 (因爲您從一個至少需要一點時間的URL加載它們)。

所以,你必須讓它重新加載你完成加入下載圖片後:

collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    .... 
    self.reloadData() 
} 

或課程,你可以給它的項目的一個固定金額的部分,如果你知道正手這一數額:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return 5//whatever amount 
} 

當然,這將是更好的異步加載圖像凍結您的應用程序時,沒有互聯網連接的存在阻止它,但是這不是問題的一部分。

+0

如何。我可以這樣做嗎?你能告訴我一個鏈接或水手嗎??或者至少需要什麼? –

+0

在'cellForItemAt ...'裏面調用'self.reloadData()'?不應該那樣做。正確的答案是使用DispatchQueue.main.async。 – nathan

+0

@rexhin上面鏈接的問題標記爲「可能的重複」,包含您需要的所有信息。 – nathan

0

這是因爲在第一次加載你的陣列images.count = 0

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    return images.count 
} 

因爲圖片數組爲空

,如果你的項目的數量爲0,你的應用是不是在func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell進入。