这里是xib拖的控件
代码:
class ViewController: UIViewController,UIScrollViewDelegate { let WIDTH : Double = Double(UIScreen.main.bounds.size.width) //当前的 @IBOutlet weak var oneBtn: UIButton! @IBOutlet weak var twoBtn: UIButton! @IBOutlet weak var threeBtn: UIButton! @IBOutlet weak var scrollView: UIScrollView! var vcArr = [UIViewController]()//这里是字ViewController的数组 override func viewDidLoad() { super.viewDidLoad() addChildController() } @IBAction func oneBtnClick(_ sender: Any) { self.oneBtn.isSelected = true; self.twoBtn.isSelected = false; self.threeBtn.isSelected = false; self.scrollView.setContentOffset(CGPoint.init(x: WIDTH*0, y: 0), animated: true) } @IBAction func twoBtnClick(_ sender: Any) { self.oneBtn.isSelected = false; self.twoBtn.isSelected = true; self.threeBtn.isSelected = false; self.scrollView.setContentOffset(CGPoint.init(x: WIDTH*1, y: 0), animated: true) } @IBAction func threeBtnClick(_ sender: Any) { self.oneBtn.isSelected = false; self.twoBtn.isSelected = false; self.threeBtn.isSelected = true; self.scrollView.setContentOffset(CGPoint.init(x: WIDTH*2, y: 0), animated: true) } func addChildController(){ for _ in 0...2 { let vc:UIViewController = UIViewController.init(); self.addChild(vc) vcArr.append(vc) } self.scrollView.contentSize = CGSize.init(width:WIDTH * 3.0 , height: 0) scrollViewDidEndScrollingAnimation(self.scrollView) } /** scrollview动画结束调用的方法 */ public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView){ let width = scrollView.frame.size.width; let height = scrollView.frame.size.height; let page = Int(scrollView.contentOffset.x/width) if(page == 0){ oneBtnClick(self.oneBtn) }else if(page == 1){ twoBtnClick(self.twoBtn) }else if(page == 2){ threeBtnClick(self.threeBtn) } let vc = vcArr[page] if(vc.isViewLoaded){ return; } vc.view.frame = CGRect.init(x: width * CGFloat(page), y: 0, width: width, height: height) self.scrollView.addSubview(vc.view) if(page == 0){ vc.view.backgroundColor = UIColor.red }else if(page == 1){ vc.view.backgroundColor = UIColor.blue }else if(page == 2){ vc.view.backgroundColor = UIColor.gray } } /** scrollview手动滑动结束调用的方法 */ public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewDidEndScrollingAnimation(self.scrollView) let page = Int(scrollView.contentOffset.x/scrollView.frame.size.width) if(page == 0){ oneBtnClick(self.oneBtn) }else if(page == 1){ twoBtnClick(self.twoBtn) }else if(page == 2){ threeBtnClick(self.threeBtn) } } }