[英]Delegate declared in UIView subclass won't work in UIViewController?
I'm trying to create a reusable UIView that I can place in multiple UIViewControllers. 我正在尝试创建一个可重用的UIView,我可以放在多个UIViewControllers中。 I gave it delegate methods that I want the parent UIViewControllers to access, but it throws me an error (commented in the code below).
我给它委托方法,我希望父UIViewControllers访问,但它会抛出一个错误(在下面的代码中评论)。 What's a better way I can solve this?
我能解决这个问题的更好方法是什么?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var cameraView: CameraView!
override func viewDidLoad() {
super.viewDidLoad()
self.cameraView.delegate = self
//ERROR: Cannot assign a value of type 'viewController' to a value of type 'CameraViewDelegate?'
}
}
protocol CameraViewDelegate {
func cameraViewShutterButtonTapped()
func cameraViewimagePickerTapped(imageData: NSData)
}
class CameraView: UIView {
var delegate:CameraViewDelegate?
//Ect...
}
You have not specified that ViewController
conforms to the CameraViewDelegate
protocol. 您尚未指定
ViewController
符合CameraViewDelegate
协议。 You should amend your code to this: 你应该修改你的代码:
class ViewController: UIViewController, CameraViewDelegate {
…at which point Xcode will complain that you have not implemented cameraViewShutterButtonTapped()
and cameraViewimagePickerTapped()
, which at least tells you that you're on the right track! ...此时Xcode会抱怨你没有实现
cameraViewShutterButtonTapped()
和cameraViewimagePickerTapped()
,这至少告诉你你是在正确的轨道上!
Side note: do you really want the camera view to have a strong reference to its delegate? 旁注:你真的希望摄像机视图能够强烈引用其代理吗? You might want that to be
weak
. 你可能希望它变
weak
。
您需要让ViewController类实现CameraViewDelegate协议,如下所示:
class ViewController : UIViewController, CameraViewDelegate { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.