为什么reloadData()不工作?

时间:2017-01-23 21:40:31

标签: swift collections view uicollectionview

我在两个不同的应用程序中使用UICollectionView。包含一个UICollectionView,另一个不包含。 我可以使用reloadData()在视图出现时刷新CollectionView但是在应用程序中使用下面的代码,它坚持我使用self.collectionView!.reloadData()!要么 ?因为“UICollectionView没有解开”,然后当视图重新出现时它没有重新加载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
}

2 个答案:

答案 0 :(得分:0)

看起来用于填充集合视图的数据是在ViewDidLoad方法中创建的。只有在第一次显示此View Controller时才会调用此方法,而不像ViewWillAppear方法那样,每次调用View Controller时都会调用该方法。因此,即使每次显示视图控制器时collectionView都会尝试重新加载数据,但数据永远不会更改。为了获取新数据,您需要将刷新数据的代码(grabPhotos方法)移动到ViewWillAppear方法。

答案 1 :(得分:0)

似乎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!") } } } ,如下所示:

neo4j-import

希望这会有所帮助。

相关问题