Prato Das
Prato Das

Reputation: 41

How to push a UIViewController from a UIView

I am new to iOS development and I am making a left menu bar like many applications. I got to a point but now I am stuck. Please help.

I have a class called LeftMenu and it is declared as follows:

class LeftMenu: UIView, UITableViewDelegate, UITableViewDataSource {

The reason is I am using the same LeftMenu in multiple UIViewControllers

There is a tableView which represents the scrollMenu and I am observing the selected row like this:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch self.menuItems[indexPath.row] {
    case "Wever":
        print(self.menuItems[indexPath.row])
    case "Payments":
        print(self.menuItems[indexPath.row])
    case "Profile":
        print(self.menuItems[indexPath.row])
    case "Trip History":
        print(self.menuItems[indexPath.row])
    case "Referral":
        print(self.menuItems[indexPath.row])
    case "Help":
        print(self.menuItems[indexPath.row])
    case "Settings":
        print(self.menuItems[indexPath.row])
    case "About":
        print(self.menuItems[indexPath.row])
    default:
        break
    }
}

I use the LeftMenu for bringing up menu in the each of the view controller.

What I would like to do is open the corresponding view controller when a cell in the tableView is selected. Please help.

Upvotes: 0

Views: 747

Answers (1)

Sune
Sune

Reputation: 1366

You could create a delegate protocol for the LeftMenu view, and have any view controllers displaying the LeftMenu implement that protocol, so they take responsibility for pushing the new view controller.

in LeftMenu.swift

protocol LeftMenuDelegate: class {
    func leftMenuDidSelectViewController(_ viewController: UIViewController)
}

class LeftMenu: UIView, UITableViewDelegate, UITableViewDataSource {
    public weak var delegate: LeftMenuDelegate?
    ...

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch self.menuItems[indexPath.row] {
        case "Wever":
            let viewController = WeverViewController() // or whatever it is named
            self.delegate?.leftMenuDidSelectViewController(viewController)
            ...
        }
    }
    ...
}

Then in all view controllers that display LeftMenu:

class SomeViewController: UIViewController, LeftMenuDelegate {
    ...
    // wherever you create you left menu, do this
    let leftMenu = LeftMenu()
    leftMenu.delegate = self
    ...

    // Add this method to be called from LeftMenu through the delegate protocol
    func leftMenuDidSelectViewController(_ viewController: UIViewController) {
        self.navigationController?.pushViewController(viewController, animated: true)
    }

You could create a base class that does this for all the view controllers that include the LeftMenu view, so you don't have to have this implementation more than once.

Upvotes: 2

Related Questions