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

时间:2018-09-11 08:26:09

标签: ios swift uibutton uiimage phasset

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

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)
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

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