0

guys. I'm asking for help. It seems a very easy task, but I can solve it for the whole day. I'm trying to create a side menu using container view. When a user presses More button(barButtonItem), the whole view slide to the right and menu table appears. I know how to make it using Notifications. But I would like to solve it through delegation. Here is my storyboard. enter image description here

and code:

import UIKit

class RootViewController: UIViewController, SideMenuDelegate {

    @IBOutlet weak var leading: NSLayoutConstraint!

    var sideMenuIsOpen = false
    var sideMenu: MainViewController?

    override func viewDidLoad() {
        super.viewDidLoad()

        sideMenu?.delegate = self
    }

    func openSideMenu() {
        toggleSideMenu()
    }

    func toggleSideMenu() {
        if sideMenuIsOpen {
            leading.constant = 0
        } else {
            leading.constant = 240
        }
    }
}

and: import UIKit

protocol SideMenuDelegate {
    func openSideMenu()
}

class MainViewController: UIViewController {

    var delegate: SideMenuDelegate?

    @IBAction func toggleSideMenu(_ sender: UIBarButtonItem) {
        if let delegateUnwrapped = delegate {
            delegateUnwrapped.openSideMenu()
        } else {
            print("nil")
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        BackgroundImageView.createBackground(insideView: self, image: .mainViewBackground)

    }   

}

Thank you!

djaflienda
  • 31
  • 6
  • `sideMenu` seems to be `nil` the whole time – dod you forget to init the side-menu? probably, yes. – holex Jul 23 '18 at 15:56
  • Yeah, I have already understood it. But I have no idea how to fix it. It doesn't work when I try "var sideMenu = MainViewController()". – djaflienda Jul 23 '18 at 16:21

1 Answers1

0

This

var sideMenu: MainViewController? // is nil 

override func viewDidLoad() {
    super.viewDidLoad()

    sideMenu?.delegate = self
}

has no reference to the current displayed main , it's nil when you present the main from the Root give it the reference

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • I'm not sure if I understand. I'm new to programming. And make everything like Google said=) How can I give a reference? – djaflienda Jul 23 '18 at 15:54