0

I know there are some questions related to this topic, I did some research, none of them worked for me.

so I have a tableView and I am adding a collectionView Controller as child view controller to one of the cell.

here's my code in tableview controller

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        cell.contentView.backgroundColor = .red

        let vcToAdd = storyboard?.instantiateViewController(withIdentifier: "MainCollectionViewController") as? MainCollectionViewController

        self.addChildViewController(vcToAdd!)
        vcToAdd?.willMove(toParentViewController: self)
        cell.contentView.addSubview((vcToAdd?.collectionView)!)
        vcToAdd?.didMove(toParentViewController: self)

        vcToAdd!.collectionView!.translatesAutoresizingMaskIntoConstraints = false
        vcToAdd?.collectionView?.leftAnchor.constraint(equalTo: cell.contentView.leftAnchor, constant: 0).isActive = true
        vcToAdd?.collectionView?.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: 0).isActive = true
        vcToAdd?.collectionView?.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 0).isActive = true
        vcToAdd?.collectionView?.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 0).isActive = true

        return cell

    }

}

viewDidLoad in child view controller (collection view vc) is called, but not viewWillAppear and viewDidAppear, I pretty much read all related questions but still can't figure out why.

could anyone point out what might be wrong? :/

thanks

Ian
  • 239
  • 1
  • 14
  • 1
    You should not be calling `vcToAdd?.willMove` when adding a child controller, that's called from `addChildViewController` But the problem is that `cell` is not in the view hierarchy yet when you call `didMove`. – Sulthan Apr 24 '17 at 14:52
  • @Sulthan , thanks for replying. when should I call `didMove` ? in parent `viewDidAppear` maybe ? – Ian Apr 24 '17 at 15:08
  • 1
    Call `addChildViewController` first, followed by `didMoveToParentViewController(self)`. Then call `addSubView(vcToAdd.view)`.. then add your `collectionView`. – Brandon Apr 24 '17 at 17:39
  • Might be of use: http://stackoverflow.com/a/39161026/148206 – Craig McMahon Apr 24 '17 at 20:49

0 Answers0