【发布时间】:2024-01-19 00:38:01
【问题描述】:
嗨,我目前在 iOS 10 + Swift 3 上遇到了 UICollectionView 的问题。一旦我的视图加载了每个单元格中的 ImageView,就会随机变为空白,其中一些可以加载。
现在我必须在重新加载 CollectionView 的数据之前延迟,但它仍然不能 100% 解决我的问题,有时我的单元格仍然是空白的。
视图控制器
@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存储文件路径,所有图像都保存在文档目录中。
【问题讨论】:
标签: ios swift uicollectionview