2017-09-22 14 views
0

您好我目前在iOS 10 + Swift 3上遇到了與UICollectionView有關的問題。一旦我的View在每個單元格中加載了ImageView隨機空白,其中一些可以加載。UICollectionview未完全加載CoreData的圖像獲取隨機空白單元格圖像

Here is my random output

現在我已經得到的CollectionView的我reloadData之前的延遲,但它仍然不能100%解決我的問題,有時我的手機還是空白。

的ViewController

@IBOutlet weak var petCollection: UICollectionView! 
var petObj: [Pet] = [] 

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! PetCollectionViewCell 

    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory 
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask 
    let paths    = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) 

    let dirPath   = paths.first! 
    let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(petObj[indexPath.item].petImage!) 
    let image = UIImage(contentsOfFile: imageURL.path) 

    cell.collectionViewImage.image = image 

    return cell 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.petCollection.delegate = self 
    self.petCollection.dataSource = self 
} 
override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 
    DispatchQueue.main.asyncAfter(deadline: .now() + 1) { 
     petCollection.reloadData() 
    } 
} 

UICollectionViewCell

class PetCollectionViewCell: UICollectionViewCell { 
    @IBOutlet weak var collectionViewImage: UIImageView! 
} 

我的假設是reloadData調用前UICollectionView完成創建細胞。

我用CoreData存儲文件路徑,並且所有的圖像都保存在文檔目錄中。

回答

0

是的,當viewDidLoad被調用時,當你的用戶進入這個視圖控制器時,你的集合視圖將加載它的數據。

而不是使用延遲重新加載數據異步,你應該使用這個庫的:

https://github.com/rs/SDWebImage

它會處理你的圖像的異步加載。

您可以使用這樣的庫:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! PetCollectionViewCell 

    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory 
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask 
    let paths    = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) 


    cell.collectionViewImage.sd_setImage(with: URL(string: "yourPathToImage"), placeholderImage: UIImage(named: "placeholder.png")) 

    return cell 
} 
+0

可以與本地圖像文件庫的使用?因爲我使用CoreData來存儲保存在文檔目錄中的圖像路徑。 – Totally

+0

是的,你也可以使用本地圖像。檢查了這一點:https://stackoverflow.com/questions/37970124/storing-and-retrieving-images-from-documents-directory-in-tableview – Kingalione

+0

我試過上面的代碼後,仍然發生問題https://ibb.co/kxhaKQ如果你看到它的圖像加載只有3三個圖片和其他人仍然是佔位符圖像(人類圖標)我是否需要reloadData的地方? – Totally