如何将资产转换为 UIImages 以在 UICollectionView 中显示照片?

How do I convert assets to UIImages to display photos within a UICollectionView?

我一直在使用 DKImagePickerController 库 select 并显示 iPhone 照片库中的多张图片,我的目标是显示 selected UICollection视图中的图像。资产首先作为 'DKAsset' 类型的数组从一个视图控制器传递到另一个视图控制器('Preview' 视图控制器),我相信这是库所需要的。预览 VC 是我试图在 Collection 视图中显示照片的地方。

为此,我尝试将 DKAssets 转换为 UIImages,然后将它们存储在 UIImage 类型的空数组中。也许我这里的方法有缺陷,但我无法将资产转换为 UIImages(即 viewDidLoad returns 中的 'print(images)' 语句是一个空数组),尽管 end-goal 只是在 Collection 视图中显示照片。

谁能帮我弄清楚如何实现这一目标?我的代码如下。非常感谢。

class PreviewImageViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet var collectionView: UICollectionView!

var assets: [DKAsset] = []
var images: [UIImage] = []

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.dataSource = self
    collectionView.delegate = self
    print(assets)
    
    convertAssetsToImages()
    //the print statement below return an empty array, so something is not working
    print(images)
}

//the function below is how I've been attempting to convert DKAssets to UIImages, in order to store them in the empty UIImage array.
func convertAssetsToImages() {
    for asset in assets {
        asset.fetchOriginalImage(completeBlock: {(image, info) in
            
            self.images.append(image!)

        })
    }
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
    //the 'previewImage' below is an IBOUtlet of a UIImageView in another Swift file called 'CollectionViewCell'
    cell.previewImage.image = images[indexPath.item]
    return cell
} 
}

我认为 print(images) 在块完成之前触发,这就是为什么它仍然是空的。您可以测试打印到 convertAssetsToImages() 块中的日志,以查看什么时候触发。一种可能的解决方案是删除 UIImage 数组以拥有一个数组(更易于管理)并将资产转换为 collectionView cellForRow

上的 UIImage

代码如下所示:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
    
    // Get asset at indexPath
    let asset = assets[indexPath.item]
    asset.fetchOriginalImage(completeBlock: {(image, info) in
        
        if let image = image {
            cell.previewImage.image = image
        }
    })
    
    
    return cell
}

并且不要忘记在 viewDidLoad

中调用 collectionView.reloadData()
override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.reloadData()
    print(assets)
}

您可以删除 UIImage 数组和任何引用它的东西

希望这有帮助 - 如果它不起作用请告诉我,我会 运行 代码并帮助您找到解决方案