Search code examples
iosswiftuitableviewuinavigationcontroller

How to push a view from inside a UITableViewCell that is in a UICollectionViewCell?


I have a UITableView inside of a UICollectionViewCell and I'm trying to push a new view from the UITableViewCell inside of the tableView(_:didSelectRowAt:) method. However, I cannot access navigationController. How would I go about navigating to the new view?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var item = Item(name: "")

    switch indexPath.section {
    case 0:
        item = array1![indexPath.item]
    case 1:
        item = array2![indexPath.item]
    default:
        break
    }

    let layout = UICollectionViewFlowLayout()
    let newView = NewCollectionView(collectionViewLayout: layout)
    newView.itemOfInterest = item

    // Can't reference navigationController
}

Solution

  • Get parent controller of current View -

    //MARK: get parent controller...
    extension UIView {
        var parentViewController: UIViewController? {
            var parentResponder: UIResponder? = self
            while parentResponder != nil {
                parentResponder = parentResponder!.next
                if let viewController = parentResponder as? UIViewController {
                    return viewController
                }
            }
            return nil
        }
    }
    

    Usage:- Get navigationController reference as parentViewController?.navigationController

    let viewController = GymLearnMoreViewController(nibName: "GymLearnMoreViewController", bundle: nil) //Your View controller instance
    parentViewController?.navigationController?.pushViewController(viewController, animated: true)
    

    Source Apple:-

    https://developer.apple.com/documentation/uikit/uiresponder/1621099-next https://developer.apple.com/documentation/uikit/uiresponder?changes=_9