Swift 使用UISCrollView展示多個檢視控制
import UIKit
class PageViewController: UIViewController,UIScrollViewDelegate {
var scrollView = UIScrollView()
var pageControl = UIPageControl()
var isPageControlUse = false //新增一個狀態,用來標記頁面的滑動狀態
override func viewDidLoad() {
super.viewDidLoad()
var rect = UIScreen.main.bounds
let width :CGFloat = UIScreen.main.bounds.width
let height : CGFloat = UIScreen.main.bounds.height
scrollView.frame = rect
scrollView.isPagingEnabled = true //設定按頁顯示
scrollView.contentSize = CGSize(width: width * 2, height: height)
scrollView.backgroundColor = UIColor.black
scrollView.delegate = self
let pcHei : CGFloat = 50.0
let pcRect = CGRect(x: 0, y: height - pcHei, width: width, height: pcHei)
pageControl.frame = pcRect
pageControl.numberOfPages = 2
pageControl.currentPage = 0
pageControl.backgroundColor = UIColor.gray
pageControl.addTarget(self, action: #selector(pageControlDidChange(sender:)), for: UIControl.Event.valueChanged)
let firstVC = FirstViewController()
rect.origin.x = 0.0
firstVC.view.frame = rect
let secondVC = SecondViewController()
rect.origin.x = rect.size.width
secondVC.view.frame = rect
scrollView.addSubview(firstVC.view)
scrollView.addSubview(secondVC.view)
self.view.addSubview(scrollView)
self.view.addSubview(pageControl)
}
// pageControl點選事件
@objc private func pageControlDidChange(sender:AnyObject){
let crtPage = (CGFloat)(pageControl.currentPage)
var frame = scrollView.frame
frame.origin.x = frame.size.width * crtPage
frame.origin.y = 0
scrollView.scrollRectToVisible(frame, animated: true)
isPageControlUse = true
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 如果是通過頁面控制器物件切換頁面,則不執行後面的程式碼
if(!isPageControlUse){
let pageWith = scrollView.frame.size.width
let page = floor((scrollView.contentOffset.x - pageWith/2)/pageWith)//-1~0
pageControl.currentPage = Int(page + 1)
}
}
// Decelerating停止減速
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
isPageControlUse = false;
}
}