在UIView子类中声明的委托不能在UIViewController中工作吗?

时间:2015-07-06 22:42:49

标签: ios xcode swift

我正在尝试创建一个可重用的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...
}

2 个答案:

答案 0 :(得分:5)

您尚未指定ViewController符合CameraViewDelegate协议。您应该将代码修改为:

class ViewController: UIViewController, CameraViewDelegate {

......此时Xcode会抱怨你没有实施cameraViewShutterButtonTapped()cameraViewimagePickerTapped(),这至少会告诉你,你已经走上正轨!

旁注:你真的希望摄像机视图能够强烈引用其代理吗?您可能希望这是weak

答案 1 :(得分:4)

您需要让ViewController类实现CameraViewDelegate协议,如下所示:

class ViewController : UIViewController, CameraViewDelegate { ... }