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

Xcode13中SignUpViewController无法赋值给图片选择器代理的错误

解决Xcode13中Cannot assign value of type 'SignUpViewController' to type '(UIImagePickerControllerDelegate & UINavigationControllerDelegate)?'错误

问题核心原因

你的代码存在控制器类名不匹配的问题:

  • presentPicker()方法属于SignUpViewController,但你给SignInViewController添加了UIImagePickerControllerDelegate和UINavigationControllerDelegate的协议扩展。
  • 当前的self(SignUpViewController实例)并未遵守所需协议,因此无法赋值给picker.delegate。

修复步骤

将协议扩展的类名从SignInViewController改为SignUpViewController,确保协议实现与当前控制器对应:

@objc func presentPicker(){
    let picker = UIImagePickerController()
    picker.sourceType = .photoLibrary
    picker.allowsEditing = true
    picker.delegate = self // 错误将被修复
    self.present(picker, animated: true, completion: nil)
}


// 修改扩展的所属类为SignUpViewController
extension SignUpViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let imageSelected = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
            avatar.image = imageSelected
        }

        if let imageOriginal = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            avatar.image = imageOriginal
        }
        
        picker.dismiss(animated: true, completion: nil)
    }
}

可选优化

你也可以在SignUpViewController的类定义中显式声明协议(Swift中扩展实现协议后类自动遵守,此步骤可选):

class SignUpViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    // 类内容
}

内容的提问来源于stack exchange,提问作者Anna B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:10:37