【发布时间】:2018-07-04 06:32:58
【问题描述】:
我正在使用此代码(来自this 答案)以及分段控件在容器视图中的视图控制器之间切换,同时我正在使用它在第二个容器视图中显示另一个视图控制器相同的视图控制器。因此,我不得不注释掉删除先前 VC 的原始代码,以便嵌入两个容器视图。 (1)我怎么还能清理以前的VC? (2) 请注意,我也在向子 VC 注入依赖项,这样可以吗?
class ViewEmbedder {
class func embed(parent:UIViewController,date: Date, container:UIView, child:UIViewController, previous:UIViewController?){
// if let previous = previous {
// print("previous = \(previous.description)")
//// if previous != ScoreAndStatsTableViewController {
//// //remove
//// }
//
// removeFromParent(vc: previous)
// }
child.willMove(toParentViewController: parent)
if let hdtvc = child as? HealthDataTableViewController {
hdtvc.startDate = date
}
if let idtvc = child as? IceDataTableViewController {
idtvc.startDate = date
}
if let stvc = child as? ShiftTableViewController {
stvc.startDate = date
}
parent.addChildViewController(child)
container.addSubview(child.view)
child.didMove(toParentViewController: parent)
let w = container.frame.size.width;
let h = container.frame.size.height;
child.view.frame = CGRect(x: 0, y: 0, width: w, height: h)
}
class func removeFromParent(vc:UIViewController){
vc.willMove(toParentViewController: nil)
vc.view.removeFromSuperview()
vc.removeFromParentViewController()
}
class func embed(withIdentifier id:String, startDate: Date, parent:UIViewController, container:UIView, completion:((UIViewController)->Void)? = nil){
let vc = parent.storyboard!.instantiateViewController(withIdentifier: id)
embed(
parent: parent,
date: startDate,
container: container,
child: vc,
previous: parent.childViewControllers.first
)
completion?(vc)
}
}
用法:
class KingViewController: UIViewController {
var startDate = Date()
@IBOutlet weak var topContainerView: UIView!
@IBOutlet weak var bottomContainerView: UIView!
@IBAction func controlDidChange(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
ViewEmbedder.embed(withIdentifier: "IceDataTableViewController", startDate: startDate, parent: self, container: bottomContainerView) { (bvc) in
}
case 1:
ViewEmbedder.embed(withIdentifier: "HealthDataTableViewController",startDate: startDate, parent: self, container: bottomContainerView) { (bvc) in
}
case 2:
ViewEmbedder.embed(withIdentifier: "ShiftTableViewController", startDate: startDate, parent: self, container: bottomContainerView) { (stvc) in
}
【问题讨论】:
-
您可以使用这个第三方库,因为它也提供了很多自定义功能 -> github.com/PageMenu/PageMenu
-
感谢@MuhammadWaqasBhati,它看起来确实很棒,但我尽量避免第三方依赖,这样我就可以控制自己的代码库
标签: ios swift uiviewcontroller uicontainerview