先上效果图
Paste_Image.png Paste_Image.png首先定义3个UIViewController
//全局变量
var chatVC:UIViewController! //第一个
var friendVC:UIViewController! //第二个
var currentVC:UIViewController! //公共变量
在viewDidLoad中初始化Controller
override func viewDidLoad() {
super.viewDidLoad()
//根据storyboard获取 建议 Identifier名称与文件名相同
chatVC = self.storyboard?.instantiateViewControllerWithIdentifier("KIMListViewController") as! KIMListViewController
self.addChildViewController(chatVC)
friendVC = self.storyboard?.instantiateViewControllerWithIdentifier("KFriendTableViewController") as! KFriendTableViewController
self.view.addSubview(chatVC.view)
currentVC = chatVC
}
然后拖拽一个SegmentedControl事件方法
@IBAction func ChangeVC(sender: AnyObject) {
let seg = sender as! UISegmentedControl
switch seg.selectedSegmentIndex{
case 0:
self.replaceController(oldController: currentVC, newController: chatVC)
break
case 1:
self.replaceController(oldController: currentVC, newController: friendVC)
break
default:break
}
}
这里需要一个公共方法来切换Controller
func replaceController(oldController oldController:UIViewController,newController:UIViewController)
{
//判断同意Controller不执行切换操作
if oldController == newController {return}
self.addChildViewController(newController)
/**
* 着重介绍一下它
* transitionFromViewController:toViewController:duration:options:animations:completion:
* fromViewController 当前显示在父视图控制器中的子视图控制器
* toViewController 将要显示的姿势图控制器
* duration 动画时间(这个属性,old friend 了 O(∩_∩)O)
* options 动画效果(渐变,从下往上等等,具体查看API)
* animations 转换过程中得动画
* completion 转换完成
*/
self.transitionFromViewController(oldController, toViewController: newController, duration: 0.2, options:.TransitionNone, animations: nil) { (finished:Bool) -> Void in
if finished{
newController.didMoveToParentViewController(self)
oldController.willMoveToParentViewController(nil)
oldController.removeFromParentViewController()
self.currentVC = newController
}else{
self.currentVC = oldController
}
}
}
运行 就可以看到效果啦,大家可以试试
网友评论