I have a view controller with a segmented control in the navigation bar that switches the child view controller pithing the parent controller. It works fine but the table view I have as a child vc is not the correct size. It gets cut off at the bottom.
Parent VC:
import UIKit
class ShareTabViewController: UIViewController {
let segementedControl = UISegmentedControl(items: ["Share", "Blog", "Progress"])
override func viewDidLoad() {
super.viewDidLoad()
self.segementedControl.sizeToFit()
self.segementedControl.tintColor = Constants.Colors.raPurple
self.segementedControl.selectedSegmentIndex = 0
self.segementedControl.addTarget(self, action: #selector(selectionChanged(_:)), for: .valueChanged)
self.navigationItem.titleView = self.segementedControl
let shareVC = ShareTableViewController()
self.view.addSubview(shareVC.view)
self.addChild(shareVC)
shareVC.didMove(toParent: self)
}
@objc func selectionChanged(_ sender: UISegmentedControl) {
for subview in self.view.subviews {
subview.removeFromSuperview()
}
for childVC in self.children {
childVC.removeFromParent()
}
switch sender.selectedSegmentIndex {
case 0:
let shareVC = ShareTableViewController()
self.view.addSubview(shareVC.view)
self.addChild(shareVC)
case 1:
let blogVC = BlogViewController()
self.view.addSubview(blogVC.view)
self.addChild(blogVC)
case 2:
let progressVC = ProgressViewController()
self.view.addSubview(progressVC.view)
self.addChild(progressVC)
default:
print("default")
}
}
}
You need to set a frame for the add in selectionChanged
& in viewDidLayoutSubviews
for the add in viewDidLoad
as it has the wrong frame , or generally use
NSLayoutConstraint.activate([
shareVC.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
shareVC.view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
shareVC.view.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
shareVC.view.bottomAnchor.constraint(equalTo:self.view.safeAreaLayoutGuide.bottomAnchor)
])