gpt4 book ai didi

ios - 使用具有默认委托(delegate)实现的另一个协议(protocol)将委托(delegate)分配给一个类?

转载 作者:行者123 更新时间:2023-11-30 12:51:36 24 4
gpt4 key购买 nike

我有一个协议(protocol) ImagePickerPresentable:

protocol ImagePickerPresentable {
var imagePicker: UIImagePickerController? { get set }
func presentImagePicker(withSourceType: UIImagePickerControllerSourceType) throws
func dismissImagePicker()
weak var delegate: ImagePickerPresentableDelegate? { get set }
}

我有一个默认实现这两个功能的扩展。

extension ImagePickerPresentable where Self: UIViewController

ImagePickerPresentableDelegate:

protocol ImagePickerPresentableDelegate: class {
func imagePicker(imagePicker: UIImagePickerController, didFinishPickingImage image: UIImage?, withSuccess success: Bool)
}

我尝试扩展 ImagePickerPresentable 以默认实现 imagePicker 委托(delegate)函数:

extension ImagePickerPresentable where Self: UIImagePickerControllerDelegate & UINavigationControllerDelegate {

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissImagePicker()
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// No Callback
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
delegate?.imagePicker(imagePicker: picker, didFinishPickingImage: editedImage, withSuccess: true)
} else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
delegate?.imagePicker(imagePicker: picker, didFinishPickingImage: originalImage, withSuccess: true)
} else {
delegate?.imagePicker(imagePicker: picker, didFinishPickingImage: nil, withSuccess: false)
}
}
}

在采用该协议(protocol)的 View Controller 中,我将 self 指定为 imagePicker 委托(delegate),但是当 imagePicker 完成选取媒体时,ImagePickerPresentable 没有得到回调。

如果我直接在 View Controller 中实现图像选择器委托(delegate)函数,我确实会得到回调。我可以在协议(protocol)中设置一个函数来处理图像选择器委托(delegate)函数输出,但是是否可以让图像选择器委托(delegate)直接使用 ImagePickerPresentable 委托(delegate)函数的默认实现?

由于我的 View Controller 符合 ImagePickerPresentable、UIImagePickerControllerDelegate 和 UINavigationControllerDelegate,我认为 ImagePickerPresentable 扩展中的委托(delegate)函数将被 imagePicker 委托(delegate)识别。

最佳答案

您可以使用多播委托(delegate)来实现此目的。

关于ios - 使用具有默认委托(delegate)实现的另一个协议(protocol)将委托(delegate)分配给一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40880137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com