Adding Child View Controller view to dynamic UITableViewCell

Tometoyou picture Tometoyou · Jun 13, 2015 · Viewed 10k times · Source

How can I add a view of a child view controller to a custom UITableViewCell? I can add the view like this inside cellForRowAtIndexPath:

self.addChildViewController(controlsViewController)
cell!.cellView.addSubview(controlsViewController.view)
controlsViewController.didMoveToParentViewController(self)

But when the cell disappears, I need to remove this child view controller. I'm not really sure how to do that. Is there a better way to go about this?

Answer

Chandramani picture Chandramani · Nov 7, 2016

Do it via delegation. I have done on collection view ,you can do it on tableview too. follow the below steps

1 .In your custom cell class create a delegateHandler and override your awakeFromNib() method. eg

protocol BibleReadingSliderProtocol: class {
    func addThisViewControllerAsChild(audioViewController :AudioViewController)
}

class BibleReadingSliderCollectionCell: UICollectionViewCell {

    @IBOutlet weak var containerView: UIView!

    var audioVC = AudioViewController()
    weak var bibleReadingSliderDelegate:BibleReadingSliderProtocol?

    override func awakeFromNib() {
        super.awakeFromNib()

        print("Awake call from cell")
        // Initialization code

         let storyboard = UIStoryboard(name: "Main", bundle: nil)
        audioVC  = storyboard.instantiateViewController(withIdentifier: "AudioViewController") as! AudioViewController
        audioVC.view.frame = self.containerView.bounds
        self.containerView.addSubview(audioVC.view)

        if self.bibleReadingSliderDelegate != nil {
            self.bibleReadingSliderDelegate?.addThisViewControllerAsChild(audioViewController: audioVC)
        }

    }
}
  1. In your ViewController where you are using this custome cell (either tableview or collection view) define the delegate hander

    func addThisViewControllerAsChild(audioViewController: AudioViewController) {
        self.addChildViewController(audioViewController);
     }
    

And Dont forget to set your delegate to this viewcontroller in cellForItemAt/cellForRowAt

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let imageSliderCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! BibleReadingSliderCollectionCell

    imageSliderCollectionViewCell.bibleReadingSliderDelegate = self
    return imageSliderCollectionViewCell
}