Storyboard
Viewcontroller Code:
viewcontroller.swift//testaddchildviewcontroller////Created by Fran on 16/2/18.//copyright©2016 year kimree. All rights Reserved.//import Uikitclass Viewcontroller:uiviewcontroller {@IBOutlet weak var scrollmenu:uiscrollview! Let Colorarray = [Uicolor.whitecolor (), Uicolor.redcolor (), Uicolor.graycolor (), Uicolor.yellowcolor (), UIColo R.bluecolor ()] var buttonvcmapping: [Uibutton:uiviewcontroller] = [:] var currentvc:uiviewcontroller! Override Func Viewdidload () {super.viewdidload ()//Do any additional setup after loading the view, typical Ly from a nib. If we don't add this navigationcontroller, ScrollView's contentoffset will automatically change to fit Self.automaticallyadjustsscrollviewinsets = FAL Se scrollmenu.backgroundcolor = uicolor.redcolor () Self.navigationcontroller?. Navigationbar.backgroundcolor = Uicolor.redcolor () addscrollmenubuttons ()} override Func Didreceivem Emorywarning () { Super.didreceivememorywarning ()//Dispose of any of the resources that can is recreated. } override func Viewdidappear (Animated:bool) {super.viewdidappear (animated)}//Add ScrollView above button Func addscrollmenubuttons () {//Scrollmenu height = 50 known for var i = 0; i < 5; i++ { Let button = UIButton (type:UIButtonType.Custom) button.settitle ("button\ (i)", Forstate:uicontrolsta Te. Normal) Button.frame = CGRectMake (CGFloat (i *) + 5, +, +) Scrollmenu.addsubview (button) Record the mapping between the button and the corresponding Viewcontroller to be displayed addbuttonvcmapping (button, index:i) button click event Button.addtarget (Self, Action: "Menubuttonclick:", ForControlEvents:UIControlEvents.Touc hupinside)} scrollmenu.contentsize = Cgsizemake (CGFloat (5 *) + Ten)}//Button an D Viewcontroller mapping func AddButtonVcmapping (Button:uibutton, index:int) {Let VC = Uiviewcontroller () vc.view.frame = CGRectMake (0, 64 + 50, Uiscreen.mainscreen (). Bounds.width, Uiscreen.mainscreen (). bounds.height-64-50) Vc.view.backgroundColor = Colora Rray[index] Buttonvcmapping[button] = VC Self.addchildviewcontroller (VC)//Set the initial display which A Childviewcontroller if index = = 0{Self.view.addSubview (vc.view) CURRENTVC = VC} }//Click on the button on ScrollView to toggle the corresponding Childviewcontroller func Menubuttonclick (Button:uibutton) {Let ToVC = bu Ttonvcmapping[button] if ToVC! = Nil && ToVC! = currentvc{//Toggle Interface Display Childviewcontro Ller Self.transitionfromviewcontroller (CURRENTVC, toviewcontroller:tovc!, duration:0.5, Options:uiviewanimat Ionoptions.transitioncrossdissolve, Animations:nil, completion: {(Finished:bool), Void in if finish ed{Tovc!. Didmovetoparentviewcontroller (self) self.currentVC.willMoveToParentViewController (nil) SELF.CURRENTVC = ToVC}}}}}
The results are as follows:
Initial, default using Button0 's Childviewcontroller
Button0
Button1
Button2
Button3
Button4
IOS Childviewcontroller using the sample