Search code examples
iosswiftcontainerstableview

How can I access the rows in sections in my container?


I created a side menu programmatically with two sections (4 + 2 rows). My main controller is a UIViewController. In order to create a grouped table view with different sections within my view controller I had to place a container view inside of my of it and embedding in my other VC with the table view.

To access my rows in different sections I created an Enum first:

enum MenuType: Int, CaseIterable {

    case a, b, c, d
    case e, f

    var section: Int {
        switch self {
        case .a, .b, .c, .d : return 0
        case .e, .f: return 1
        }
    }

    var row: Int? {
        switch self.section {
        case 0: return self.rawValue
        case 1: return self.rawValue - MenuType.allCases.filter{ $0.section < self.section }.count
        default: return nil
        }
    }
}

To call the MenuTypes in my MainVC

var didTapMenuType: ((MenuType) -> Void)?

To select the correct section with the respective rows I tried the following:

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let menuType = MenuType.allCases.first(where: { $0.section == indexPath.section && $0.row == indexPath.row }) else {return}
        dismiss(animated: true) { [weak self] in
            self?.didTapMenuType?(menuType)
        }
    }

And in my MainVC I did a Switch-Case to apply actions to the different cases:

func transition(_ menuType: MenuType)
switch menuType {
        case .a:
            // action
        case .b:
         ...

And finally call it when the user taps on the side menu button:

//button action ...
 menuViewController.didTapMenuType = { menuType in
        self.transitionToNew(menuType)

Transition works great. But when selecting a row nothing happens. It worked when my main controller was a UITableViewController. The only thing I changed was to embedding in my table view into the container of my UIViewController to gain more control of the layout (it was frustrating to layout views inside of a table view controller).

Can anyone tell me what I am missing? I guess the problem is that my tableView(disSelectRowAt:) function does not apply to the table view inside of my container!?

Sorry for the long question but I can not figure out a working solution. Thanks in advance!


Solution

  • It looks like you have not connected your tableView delegate to your viewController either in Interface Builder, or in code, in you viewDidLoad for instance:

    myTableView.delegate = self
    

    EDIT: Don't forget to make your view controller to conform to UITableViewDelegate

    class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { ... }