首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHPickerViewController的“取消按钮”不能在iOS 15中工作

PHPickerViewController的“取消按钮”不能在iOS 15中工作
EN

Stack Overflow用户
提问于 2022-07-14 06:34:59
回答 2查看 495关注 0票数 1

我使用PHPickerViewController来选择iOS 15中的用户配置文件图片,我使用的是UIKit框架。我有以下代码:

代码语言:javascript
复制
var pickerConfig = PHPickerConfiguration(photoLibrary: .shared())
pickerConfig.selectionLimit = 1
pickerConfig.filter = .images
let pickerView = PHPickerViewController(configuration: pickerConfig)
pickerView.delegate = self
self.present(pickerView, animated: true)

选择器在选择图像和委派结果时工作正常。但是,当按下Cancel按钮时,什么都不会发生,选择器也不会像预期的那样被取消。

当按下PHPickerViewController实例自己的Cancel按钮时,如何关闭它?

编辑:

PHPickerViewControllerDelegate方法的实现如下:

代码语言:javascript
复制
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult])
    {
        results.first?.itemProvider.loadObject(ofClass: UIImage.self) { [unowned self] reading , error in
            guard let image = reading as? UIImage, error == nil else
            {
                DispatchQueue.main.async {
                    picker.dismiss(animated: true)
                    self.profilePictureHasError = true
                    self.toggleDoneButtonEnabled()
                }
                return
            }
            self.profilePictureHasError = false
            DispatchQueue.main.async {
                picker.dismiss(animated: true)
                self.profilePictureHasChanged = self.userProfilePicture != image
                if self.profilePictureHasChanged
                {
                    self.profilePictureView.image = image
                    self.toggleDoneButtonEnabled()
                }
            }
        }
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-14 07:35:03

您需要在picker(_:didFinishPicking:)委托方法中自己排除选择器,当用户在单击cancel按钮时完成选择、时调用该方法。

来自苹果文档 for picker(_:didFinishPicking:)

代码语言:javascript
复制
The system doesn’t automatically dismiss the picker after calling this method.

例如:

代码语言:javascript
复制
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    // Do something with the results here
    picker.dismiss(animated: true)
}

当前委托代码只在结果数组非空时(即当用户选择了图像时)才调用picker.dismiss。当单击“取消”按钮时,将使用空结果数组调用委托方法。

通过将以下内容添加到委托方法中的代码顶部,可以解决此问题:

代码语言:javascript
复制
if results.isEmpty {
    picker.dismiss(animated: true)
    return
}
票数 3
EN

Stack Overflow用户

发布于 2022-07-14 07:08:34

您只需在objc功能中将其包装出来,以使“取消”按钮工作。

代码语言:javascript
复制
    @objc
    func didOpenPhotos() {
        lazy var pickerConfig = PHPickerConfiguration()
        pickerConfig.filter = .images
        pickerConfig.selectionLimit = 1
        let pickerView = PHPickerViewController(configuration: pickerConfig)
        pickerView.delegate = self
        self.present(pickerView, animated: true)
    }

在任何地方叫它

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72976165

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档