Swift UIScrollView懒加载的使用
这里是xib拖的控件
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | 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) } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步