我正在尝试创建一个可重用的UIView,我可以放在多个UIViewControllers中。我给它委托方法,我希望父UIViewControllers访问,但它会抛出一个错误(在下面的代码中评论)。我能解决这个问题的更好方法是什么?
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...
}
答案 0 :(得分:5)
您尚未指定ViewController
符合CameraViewDelegate
协议。您应该将代码修改为:
class ViewController: UIViewController, CameraViewDelegate {
......此时Xcode会抱怨你没有实施cameraViewShutterButtonTapped()
和cameraViewimagePickerTapped()
,这至少会告诉你,你已经走上正轨!
旁注:你真的希望摄像机视图能够强烈引用其代理吗?您可能希望这是weak
。
答案 1 :(得分:4)
您需要让ViewController类实现CameraViewDelegate协议,如下所示:
class ViewController : UIViewController, CameraViewDelegate { ... }