您好我目前在iOS 10 + Swift 3上遇到UICollectionView问题。一旦我的View加载了每个单元格中的ImageView,随机空白,其中一些可以加载。
现在我在重新加载CollectionView的数据之前给出了延迟,但是当我的单元格仍然空白时,它仍然没有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!
}
我假设是在UICollectionView完成创建单元格之前调用了reloadData。
我使用CoreData存储文件路径,所有图像都保存在文档目录中。
答案 0 :(得分: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
}