将 PHAsset 转换为 UIImage 后设置 UiButton 图像

Setting UiButton image after converting PHAsset to UIImage

您好,我正在使用以下代码从照片库中获取最后一张图片,然后将其设置为按钮,但结果显示的是默认颜色灰色,而不是图片

func loadLastImageThumb(completion: @escaping (UIImage) -> ()) {
let imgManager = PHImageManager.default()
let fetchOptions = PHFetchOptions()
 // fetchOptions.fetchLimit = 1
   fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate",  ascending: true)]
  let fetchResult = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fetchOptions)

if let last = fetchResult.lastObject {
   let options = PHImageRequestOptions()
    options.deliveryMode = .fastFormat
    options.resizeMode = .exact
    options.isSynchronous = true
    options.version = .original
    print(last)
    imgManager.requestImage(for: last, targetSize: gallery.bounds.size, contentMode: PHImageContentMode.aspectFit, options: options, resultHandler: { (image, _) in
        if let image = image {
            completion(image)
            print(image)
            print(image.size)
            print(self.gallery.bounds.size)

        }
    })
}
}

//在视图中加载

   self.loadLastImageThumb { [weak self] (image) in
    DispatchQueue.main.async {
        self?.gallery.setImage(image, for: .normal)
    }
}

代码将是 self?.gallery.setBackgroundImage(image, for: .normal)