【问题标题】:Populating UICollectionView with Images from Camera Roll使用相机胶卷中的图像填充 UICollectionView
【发布时间】:2021-06-13 00:30:18
【问题描述】:

我正在尝试创建一个 UICollectionViewController,就像 iPhone 上的“照片”应用中的那个。

这是我正在使用的代码:

import UIKit
import Photos

private let reuseIdentifier = "dataCell"

class GalleryCollectionViewController: UICollectionViewController {

var images = [PHAsset]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Register cell classes
    self.collectionView!.register(GalleryImageCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    getImages()
    // Do any additional setup after loading the view.
}

func getImages() {
    let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)
    assets.enumerateObjects({ (object, count, stop) in
       // self.cameraAssets.add(object)
        self.images.append(object)
    })

    self.images.reverse()

    self.collectionView!.reloadData()
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

// MARK: UICollectionViewDataSource

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}


override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return images.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dataCell", for: indexPath) as! GalleryImageCell
    
    let asset = images[indexPath.row]
    let ImageManager = PHImageManager.default()
    if cell.tag != 0 {
        ImageManager.cancelImageRequest(PHImageRequestID(cell.tag))
    }
    
    cell.tag = Int(ImageManager.requestImage(for: asset, targetSize: CGSize(width: 120, height: 120), contentMode: .aspectFill, options: nil, resultHandler: { (result, _) in
        cell.galleryImage?.image = result
    }))
    
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = self.view.frame.width * 0.32
    let height = self.view.frame.height * 0.179910045
    return CGSize(width: width, height: height)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 2.5
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

}

无论如何,当我加载视图时,我只会看到黑色视图。即使在视图滚动很长时间时似乎创建了单元格,图像也根本不显示。 这不是与隐私权限相关的问题,因为我已经授予对“所有照片”的访问权限,并且images 包含所有照片资产。

你知道我做错了什么吗? 提前谢谢你

【问题讨论】:

    标签: uicollectionview uicollectionviewcell swift5 phasset photokit


    【解决方案1】:

    您确定您的图像被附加到块内吗?

    无论如何,我正在通过执行以下操作在我的应用中加载 PHAsset,看看它是否对您有帮助:

    我最初是这样做的:

    let assetFetcher = PHAssetFetcher(configuration: configuration)
        assetFetcher.fetchAssets { [weak self] (fetchResult) in
            guard let `self` = self, let fetchResult = fetchResult else { return }
            self.fetchResult = fetchResult
            let assets = fetchResult.objects(at: IndexSet(integersIn: 0..<fetchResult.count))
        }
    

    所以这会从图库中加载资产,但是您可能需要根据资产是什么(视频、照片、连拍、gif 等)做一些工作。您可以查看typeIdentifier 的资产以查看哪个资产属于哪个类别,然后在那里检索相关图像。例如,如果图像只是一张照片,那么您将只使用关联的图像,但如果它是视频,那么您可能只想显示一个缩略图,它会返回给您。无论哪种方式,使用 Photos API 都可能有点乏味,但这是一次重要的学习体验。

    【讨论】:

      最近更新 更多