1 import UIKit
2
3 class PageControlViewController:UIViewController,
UIScrollViewDelegate {
4
5 var scrollView = UIScrollView()
6 var pageControl = UIPageControl()
7 var isPageControlUsed = false
8 override func viewDidLoad() {
9 super.viewDidLoad()
10 var screenFrame = UIScreen.main.bounds
11 let screenWidth = screenFrame.size.width
12 let screenHeight = screenFrame.size.height
13
14 scrollView.frame = screenFrame
15 scrollView.isPagingEnabled = true
16 scrollView.contentSize = CGSize(width:screenWidth
2, height:screenHeight)
17 scrollView.backgroundColor = UIColor.black
18 scrollView.delegate = self
19
20 let pcHeight:CGFloat = 50.0
21 let pcRect = CGRect(x:0, y:screenHeight - pcHeight,
width:screenWidth, height:pcHeight)
22
23 pageControl.frame = pcRect
24 pageControl.numberOfPages = 2
25 pageControl.currentPage = 0
26 pageControl.backgroundColor = UIColor.gray
27 pageControl.addTarget(self, action:
selector(PageControlViewController.pageControlDidChanged(_:)),
for:UIControlEvents.valueChanged)
28
29 let firstController = FirstViewController()
30 screenFrame.origin.x = 0
31 firstController.view.frame = screenFrame
32
33 let secondController = SecondViewController()
34 screenFrame.origin.x = screenFrame.size.width
35 secondController.view.frame = screenFrame
36
37 scrollView.addSubview(firstController.view)
38 scrollView.addSubview(secondController.view)
39
40 self.view.addSubview(scrollView)
41 self.view.addSubview(pageControl)
42 }
43
44 func pageControlDidChanged(_ sender:AnyObject)
45 {
46 let crtPage = (CGFloat)(pageControl.currentPage)
47 var frame = scrollView.frame
48 frame.origin.x = frame.size.width * crtPage
49 frame.origin.y = 0
50
51 scrollView.scrollRectToVisible(frame, animated:true)
52 isPageControlUsed = true
53 }
54
55 func scrollViewDidScroll(_ scrollView:UIScrollView)
56 {
57 if(!isPageControlUsed)
58 {
59 let pageWidth = scrollView.frame.size.width
60 let page = floor((scrollView.contentOffset.x -
pageWidth/2)/pageWidth) + 1
61 pageControl.currentPage = Int(page)
62 }
63 }
64
65 func scrollViewDidEndDecelerating(_ scrollView:
UIScrollView)
66 {
67 isPageControlUsed = false
68 }
69 }