使用addChildViewController可以有效节约内存,且可以方便的展示自己想展示的子控制器;下面是用swift一个简单实现跳转的过程。
class first: UIViewController {
//two,three,four分别为三个控制器
var two: Two?
var three: Three?
var four: Three?
//child测试
var addChildVCclick: UIButton?
var currentC: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blueColor()
self.setupSubview()
}
func setupSubview() {
addChildVCclick = UIButton()
self.view.addSubview(addChildVCclick!)
addChildVCclick?.frame = CGRectMake(200, 100, 20, 20)
addChildVCclick?.backgroundColor = UIColor.greenColor()
addChildVCclick?.userInteractionEnabled = true
addChildVCclick?.addTarget(self, action: "addChild", forControlEvents: .TouchDown)
}
//点击按钮实现子控制器的添加
func addChild(){
print("add child")
two = Two()
self.addChildViewController(two!)
three = Three()
self.addChildViewController(three!)
four = Three()
four!.view.backgroundColor = UIColor.brownColor()
self.addChildViewController(four!)
//只有将子控制器的view添加,才会展示出子控制器
self.view.addSubview(four!.view)
if let f = four {
//在第四个控制器中添加按钮,点击实现子控制器切换
addChildVCclick?.frame = CGRectMake(200, 120, 20, 20)
addChildVCclick?.backgroundColor = UIColor.blueColor()
addChildVCclick?.userInteractionEnabled = true
addChildVCclick?.addTarget(self, action: "changeViewController", forControlEvents: .TouchDown)
f.view.addSubview(addChildVCclick!)
currentC = f //必须设置currenC(全局属性)
}
}
func changeViewController() {
print("changeViewController")
two?.view.backgroundColor = UIColor.redColor()
self.transitionFromViewController(currentC!, toViewController: two!, duration: 1, options: .TransitionCurlUp, animations: { () -> Void in
print("animations")
}) { (com) -> Void in
print("com")
self.currentC = self.two//在这里真正实现跳转,简单方便
//跳转效果由options参数决定
}
}
}