我在导航栏中有一个带有分段控件的视图控制器,该控件将子视图控制器切换为父控制器。它工作正常,但是作为子级vc的表视图的大小不正确。它在底部被切断。
父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")
}
}
}
答案 0 :(得分:1)
您需要为selectionChanged
的添加项和viewDidLayoutSubviews
的添加项viewDidLoad
设置框架,因为它的框架错误,或者通常使用
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)
])