gpt4 book ai didi

ios - 无法覆盖 Swift 中的委托(delegate)属性

转载 作者:可可西里 更新时间:2023-10-31 23:58:05 26 4
gpt4 key购买 nike

我正在尝试制作一个类似于 ImagePickerControllerStudentPickerController:

class StudentPickerController: UINavigationController, NSCoding {
unowned(unsafe) var delegate: protocol<StudentPickerControllerDelegate, UINavigationControllerDelegate>?
}

@objc protocol StudentPickerControllerDelegate: NSObjectProtocol {
optional func studentPickerControllerDidFinishPickingStudent(student: Student)
optional func studentPickerControllerDidCancel()
}

然而,这给了我:

`Property 'delegate' with the type 'protocol<StudentPickerControllerDelegate, UINavigationControllerDelegate>?' cannot override a property with type 'UINavigationControllerDelegate?'`

当查看 UIImagePickerController 的 swift 文件时,您可以看到:

class UIImagePickerController : UINavigationController, NSCoding {    
unowned(unsafe) var delegate: protocol<UIImagePickerControllerDelegate, UINavigationControllerDelegate>?
}

protocol UIImagePickerControllerDelegate : NSObjectProtocol {
optional func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
optional func imagePickerControllerDidCancel(picker: UIImagePickerController)
}

UIImagePickerController 如何能够覆盖 delegate 但我的类不能?

我知道我可以简单地重命名我的属性来避免这种情况,但我想知道 UIImagePickerController 是如何实现这一点的。

最佳答案

So my question is how is ImagePickerController able to override delegate but my class is not?

UIImagePickerController 从 Objective-C 桥接而来,可以覆盖属性。因此,如果您真的非常需要它,那么您可能希望在 Objective-C 中实现 StudentPickerController 并在 Swift 代码中使用它的桥接版本。

如果留在 Swift 中,你可以做的是:

class StudentPickerController: UINavigationController {
private var studentDelegate: StudentPickerControllerDelegate?
override var delegate: UINavigationControllerDelegate? {
didSet { studentDelegate = delegate as? StudentPickerControllerDelegate }
}
}

关于ios - 无法覆盖 Swift 中的委托(delegate)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31730382/

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