You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHPickerViewController重新打开时如何取消之前选中的图片状态

问题原因

你当前的PHPickerViewController是在PHImagePicker初始化时全局创建的唯一实例,PHPicker本身会自动存储上次的选中状态,所以重复打开同一个实例时就会保留之前的选中标记。

最优解决方案(兼容iOS14+,无版本兼容问题)

每次弹出选择器时重新创建全新的PHPickerViewController实例即可自动清空上次选中状态,修改代码如下:

修改后的PHImagePicker代码

import UIKit
import PhotosUI

public protocol PHImagePickerDelegate: AnyObject {
    func didSelect(images: [UIImage]?)
}

class PHImagePicker: NSObject {
    // 移除原有全局pickerController常量定义
    private weak var presentationController: UIViewController?
    private weak var delegate: PHImagePickerDelegate?
    private var images = [UIImage]()
    
    public init(presentationController: UIViewController, delegate: PHImagePickerDelegate) {
        super.init()
        self.presentationController = presentationController
        self.delegate = delegate
    }
    
    private func pickerController(_ controller: PHPickerViewController, didSelect images: [UIImage]?) {
        controller.dismiss(animated: true, completion: nil)
        self.delegate?.didSelect(images: images)
    }
    
    public func present(from sourceView: UIView) {
        // 每次弹出前重新生成配置和picker实例
        var config = PHPickerConfiguration()
        config.selectionLimit = 3
        config.filter = PHPickerFilter.images
        // iOS16+如果需要预选中上次的图片可以加下面这行,不需要就省略
        // config.preselectedAssetIdentifiers = 上次选中的assetId数组
        let pickerController = PHPickerViewController(configuration: config)
        pickerController.delegate = self
        self.presentationController?.present(pickerController, animated: true)
    }
}

extension PHImagePicker: PHPickerViewControllerDelegate {
    // 原有代理逻辑保持不变即可
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        self.images = []
        picker.dismiss(animated: true, completion: nil)
        
        for result in results {
            result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] object, error in
                if let error = error {
                    print("图片加载错误:", error)
                    return
                }
                guard let self = self, let image = object as? UIImage else { return }
                self.images.append(image)
                
                if self.images.count == results.count {
                    DispatchQueue.main.async {
                        self.pickerController(picker, didSelect: self.images)
                    }
                }
            }
        }
    }
}

ViewController调用逻辑无需修改

原有的importButtonTapped方法可以直接复用,无需改动。

可选方案(仅iOS16+支持)

如果你不想每次新建picker实例,可以在弹出前给配置的preselectedAssetIdentifiers赋值为空数组,清空预选中状态,但这种方案有版本限制,优先推荐第一种方案。

内容的提问来源于stack exchange,提问作者Zhou Haibo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:48:02