简体   繁体   中英

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. I gave it delegate methods that I want the parent UIViewControllers to access, but it throws me an error (commented in the code below). 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. 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!

Side note: do you really want the camera view to have a strong reference to its delegate? You might want that to be weak .

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

class ViewController : UIViewController, CameraViewDelegate { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM