Demo with the following URL code is used.

I'm trying to edit what comes out of Container View from the bottom of the screen, RegisterPopupView. From the RegisterPopupView class, I want to execute the method in VC in the process when the button on the container view is pressed. In order to do that, we are trying to do that because delegate processing is necessary. Called Side MainPageViewController Called RegisterPopupView is as follows. (A lot of unrelated parts are omitted)

class MainpageViewController: UIViewController {
    @IBOutlet private weak var registerPopupView: RegisterPopupView!
func test () {
// do something
override func viewDidLoad () {
        super.viewDidLoad ()
     registerPopupView.delegate = self // Unexpectedly found nil while unwrapping an Optional value
class RegisterPopupView: UIView, PopupViewContainable, Nibable {
    weak var delegate: MainpageViewController?

    @IBOutlet weak var containerView: UIView! {
        didSet {
            containerView.layer.masksToBounds = true
 @IBAction func didTapRegisterButton () {

         delegate? .test ()
         registerButtonTapHandler? ()

RegisterPopupView.delegate = self and Unexpectedly found nil while unwrapping an Optional value appears because registerPopupView.delegate is nil. But I don't know how. Which should I connect to? Is it a container view or a view above it? But neither can connect. What is the problem?

It is the part of passing the VC instance to RegisterPopupViewController.delegate when the instance of "RegisterPopupViewController" is generated, but in short the following

let hoge = Hoge ()
let piyo = Piyo ()
hoge.delegate = piyo
Is it part of

? Since the agent class is VC this time, where are these instantiated? ? I'm not sure about the so-called agent. At first, I was trying to do it in viewDidLoad () like registerPopupView.delegate = self, but this meant that registerPopupView would not be instantiated and would become nil.

  • Answer # 1

    In the code of Git, it seems that the popup is generated without "RegisterPopupViewController".
    It is a part of "private let registerPopupView = RegisterPopupView.view ()" of "RegisterPopupViewController.swift".
    "RegisterPopupView.view ()" is a method defined in the protocol of "Nibable", and it seems that an instance of "RegisterPopupView" is generated from the xib file by the process in this.
    Therefore, if the event handled without "RegisterPopupView" is returned to the "MainpageViewController" class, I think that the flow will be "RegisterPopupView"->"RegisterPopupViewController"->"MainpageViewController".

    The event when the button is tapped in the container view is already handled without "RegisterPopupViewController", so how about revising this area?
    ・ RegisterPopupView.registerButtonTapHandler