swift - 为什么 reloadData() 不起作用?

标签 swift collections view uicollectionview

我在两个不同的应用程序中使用 UICollectionView。一个包含 UICollectionView,另一个则不包含。 当 View 出现时,我可以使用 reloadData() 刷新 CollectionView,但是在带有下面代码的应用程序中,它坚持我使用 self.collectionView!.reloadData() 和 !或者 ?作为“UICollectionView未展开”,然后当 View 重新出现时它不会重新加载collectionView,只有在我完全安静并重新启动应用程序时才起作用。

    class SecondViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

var imageArray = [UIImage]()
var assetCollection: PHAssetCollection = PHAssetCollection()
let albumName = "Euphoria"
var albumFound : Bool = false
var photosAsset: PHFetchResult<PHAsset>!






override func viewDidLoad() {
    super.viewDidLoad()

    let fetchOptions = PHFetchOptions()
    fetchOptions.predicate = NSPredicate(format: "title = %@", albumName)

    let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
    if let _:AnyObject = collection.firstObject{

        //found the album
        self.albumFound = true
        self.assetCollection = collection.firstObject! as PHAssetCollection

    }else{
        var albumPlaceholder:PHObjectPlaceholder!
        //create the folder
        NSLog("\nFolder \"%@\" does not exist\nCreating now...", albumName)
        PHPhotoLibrary.shared().performChanges({
            let request = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: self.albumName)
            albumPlaceholder = request.placeholderForCreatedAssetCollection
        },
                                               completionHandler: {(success, error)in
                                                if(success){
                                                    print("Successfully created folder")
                                                    self.albumFound = true
                                                    let collection = PHAssetCollection.fetchAssetCollections(withLocalIdentifiers: [albumPlaceholder.localIdentifier], options: nil)
                                                    self.assetCollection = collection.firstObject! as PHAssetCollection
                                                }else{
                                                    print("Error creating folder")
                                                    self.albumFound = false
                                                }
        })
    }



    grabPhotos()






}

override func viewWillAppear(_ animated: Bool) {

    self.collectionView!.reloadData()
}




func grabPhotos(){

    let imgManager = PHImageManager.default()

    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = true
    requestOptions.deliveryMode = .highQualityFormat

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]


    if let fetchResult : PHFetchResult = PHAsset.fetchAssets(in: self.assetCollection, options:nil){

        if fetchResult.count > 0 {

            for i in 0..<fetchResult.count{

                imgManager.requestImage(for: fetchResult.object(at: i) as PHAsset, targetSize: CGSize(width:200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {

                    image, error in

                    self.imageArray.append(image!)

                })
            }

        }
        else{
            print("you got no photos!")


        }


    }
}









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

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

    let imageView = cell.viewWithTag(1) as! UIImageView

    imageView.image = imageArray[indexPath.row]

    return cell
}

最佳答案

看来collectionView!.reloadData()viewWillAppear 之前已被调用(在 grabPhotos() 中)完成工作。

我建议通过添加两个断点来调试代码执行的排序,其中一个位于 self.collectionView!.reloadData()线和另一条线 self.imageArray.append(image!)行来检查首先到达哪一个。

而不是添加 self.collectionView!.reloadData()viewWillAppear ,您可能需要将其添加到 grabPhotos() 中追加到 imageArray 后的方法,如下:

override func viewWillAppear(_ animated: Bool) {
    // remove it from here
}

func grabPhotos() {
    let imgManager = PHImageManager.default()

    let requestOptions = PHImageRequestOptions()
    requestOptions.isSynchronous = true
    requestOptions.deliveryMode = .highQualityFormat

    let fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    if let fetchResult : PHFetchResult = PHAsset.fetchAssets(in: self.assetCollection, options:nil){
        if fetchResult.count > 0 {
            for i in 0..<fetchResult.count{
                imgManager.requestImage(for: fetchResult.object(at: i) as PHAsset, targetSize: CGSize(width:200, height: 200), contentMode: .aspectFill, options: requestOptions, resultHandler: {
                    image, error in
                    self.imageArray.append(image!)
                })
            }

            // there we go...
            self.collectionView!.reloadData()

        } else{
            print("you got no photos!")
        }
    }
}

希望这有帮助。

关于swift - 为什么 reloadData() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41816168/

相关文章:

c# - 使用 foreach() 从集合中删除多个实体?

java - joda ArrayIntList(5000000) 与 int[5000000] 内存消耗

objective-c - 什么类型的代码正确 : addSubview or direct controller assignment in AppDelegate?

ios - TableView 的观察值

ios - 是否可以在 Realm 迁移中重命名和更改属性的数据类型

ios - Spritekit - 如何创建一个像台球口袋一样的洞?

ios - 从 [String :AnyObject] to unrelated type NSMutableDictionary always fails Warning

swift - 了解 Swift 索引、范围、距离

mvvm - 用于添加和编辑的多个ViewModel(WPF,MVVM)

ios - 如何使用自动布局对 View 进行动画更改 View 层次结构?