iosswiftchildviewcontroller

Customizing width and height for child view controller does not work


I'm trying to set the width and height of my child view controller's frame, but it's not working. Here's what I'm trying to do:

  let frame = UIScreen.main.bounds
  let vc = FieldsTableViewController()
  addChild(vc)
  view.addSubview(vc.view)        
  vc.didMove(toParent: self)
  vc.view.frame = CGRect(x: (frame.maxX+frame.minX)/2, y: 300, width: 200, height: 5)

The x and y positions are correctly set, but no matter what I try I can't seem to set the width and the height. The weird thing is that I am using the same child vc in another vc, with the exact same code as above, and I have no problem setting the width and height there.

I also tried using Auto-Layout but was not able to make it work for a child view controller (is that possible? I didn't find any example).

Thanks for your help.


Solution

  • I found a way around it. I finally realized that the issue occurs when I set the view of my view controller, like so :

    let v = PlayerSelectionView()
    view = v
    

    I'm not sure why that caused the problem described, but adding my view as a subview instead fixed it:

    let v = PlayerSelectionView()
    v.frame = view.frame
    view.addSubview(v)
    

    Now I'm able to edit the width and height of my child view controllers.