我的问题是,当我将图片保存到照片库时,我的collectionView不会更新。如果我单击第一张图片,它将打开我最近保存的图片,但从外观上来说,collectionView不会更新。我以为reloadData()可以这样工作,但我猜不是这样。
在应用加载时,用户从collectionView(iPhone照片库)中选择照片,然后将其发送到另一个视图,在该视图中,他将照片编辑,然后将其保存到图库中,并使用展开按钮返回到第一个视图。
我的代码:
class pickerViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
var imageArray = [UIImage]()
override func viewDidLoad() {
mygtukasMenu.layer.cornerRadius = 10
mygtukasMenu.clipsToBounds = true
grabPhotos()
kolekcija.reloadData()
}
@IBOutlet weak var kolekcija: UICollectionView!
func grabPhotos(){
let imgManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = false
requestOptions.deliveryMode = .opportunistic // Quality of images
requestOptions.isNetworkAccessAllowed = true
requestOptions.isSynchronous = true
requestOptions.progressHandler = { (progress, error, stop, info) in
print("progress: \(progress)")
}
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions) {
if fetchResult.count > 0 {
for i in 0..<fetchResult.count {
imgManager.requestImage(for: fetchResult.object(at: i) , targetSize: CGSize(width: 150, height: 150), contentMode: .aspectFill, options: requestOptions, resultHandler: {
image, error in
self.imageArray.append(image!)
})
}
}
else {
print("You got no photos")
kolekcija.reloadData()
}
}
kolekcija.reloadData() // UPDATED
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
grabPhotos()
kolekcija.reloadData() // UPDATED
}
}
答案 0 :(得分:1)
当您在块中的funcgrabPhotos()获取图片时,您需要调用reloadData()
imgManager.requestImage(for: fetchResult.object(at: i) , targetSize: CGSize(width: 150, height: 150), contentMode: .aspectFill, options: requestOptions, resultHandler: {
image, error in
self.imageArray.append(image!)
self.kolekcija.reloadData() <<<<< HERE RELOAD CALL NEED
})
打电话时
override func viewDidLoad() {
mygtukasMenu.layer.cornerRadius = 10
mygtukasMenu.clipsToBounds = true
grabPhotos() <<< photos still grabbing at async mode
kolekcija.reloadData() <<< there is no images grabbed... it still grabbing at async mode when u call reload func here.....
}
答案 1 :(得分:0)
我的问题的解决方案是每次加载视图时从imageArray中删除所有图像。我不知道为什么它这么重要,但终于奏效了。而且,无需在requestImage块内调用reloadData()。 (以我为例)
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.imageArray.removeAll()
grabPhotos()
kolekcija.reloadData()
}