Swift4.0之自定义分段控制器(SegmentedControl)的简单封装

非常简单,就一个文件就解决了问题

Swift4.0之自定义分段控制器(SegmentedControl)的简单封装_第1张图片
自定义分段控制器
SwipeViewController.swift
import UIKit
/// 基于UIPageViewCotroller的切换视图
class SwipeViewController: UIViewController {
    
    /// [对外接口]
    var titles = [String]()
    /// [对外接口]
    var viewControllers = [UIViewController]()
    
    private let barView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .white
        return view
    }()
    
    private let contentView: UIView = {
        let view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        view.backgroundColor = .white
        return view
    }()
    
    private let barViewHeight: Int = 44
    
    private var pageController: UIPageViewController!
    fileprivate var indicatorView: UIView!
    private var pageScrollView: UIScrollView!
    
    fileprivate var currentIndex = 0
    
    fileprivate var isPageScrolling = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(barView)
        view.addSubview(contentView)
        layoutContentView()
        
        setUpPageViewController()
        setupBarView()
    }
    
    func layoutContentView() {
        let views: [String: Any] = ["topLayoutGuide":topLayoutGuide,"barView":barView,"contentView":contentView,"bottomLayoutGuide":bottomLayoutGuide]
        let metrics: [String: NSNumber] = ["barViewHeight": NSNumber(value: Float(barViewHeight))]
        let horizonal1 = NSLayoutConstraint.constraints(withVisualFormat: "|[barView]|", options: .alignAllCenterY, metrics: nil, views: views)
        NSLayoutConstraint.activate(horizonal1)
        let horizonal2 = NSLayoutConstraint.constraints(withVisualFormat: "|[contentView]|", options: .alignAllCenterY, metrics: nil, views: views)
        NSLayoutConstraint.activate(horizonal2)
        let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[topLayoutGuide][barView(barViewHeight)]-(15)-[contentView][bottomLayoutGuide]", options: .alignAllCenterX, metrics: metrics, views: views)
        NSLayoutConstraint.activate(verticalConstraints)
    }
    
    func setupBarView() {
        guard titles.count > 0 else { return }
        let vcCount = viewControllers.count
        for index in 0.. currentIndex {
                for index in currentIndex...sender.tag {
                    pageController.setViewControllers([viewControllers[index]], direction: .forward, animated: true, completion: { [weak self] complete in
                        if complete {
                            self?.currentIndex = index
                        }
                    })
                }
            } else if sender.tag < currentIndex {
                for index in (sender.tag...currentIndex).reversed() {
                    pageController.setViewControllers([viewControllers[index]], direction: .reverse, animated: true, completion: { [weak self] complete in
                        if complete {
                            self?.currentIndex = index
                        }
                    })
                }
            }
        }
    }
}

extension SwipeViewController: UIPageViewControllerDataSource {
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        let index = viewControllers.index(of: viewController)
        if var index = index {
            index += 1
            if index == viewControllers.count {
                return nil
            }
            return viewControllers[index]
        } else {
            return nil
        }
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        let index = viewControllers.index(of: viewController)
        if var index = index, index > 0{
            index -= 1
            return viewControllers[index]
        } else {
            return nil
        }
    }
}

extension SwipeViewController: UIPageViewControllerDelegate {
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed {
            let last = pageViewController.viewControllers?.last
            if let lastVC = last {
                currentIndex = viewControllers.index(of: lastVC)!
            }
        }
    }
}

extension SwipeViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let xFromCenter = view.bounds.width - scrollView.contentOffset.x
        let xCoor = Int(indicatorView.bounds.width) * currentIndex
        indicatorView.frame = CGRect(x: CGFloat(xCoor-Int(xFromCenter)/viewControllers.count), y: indicatorView.frame.origin.y, width: indicatorView.frame.size.width, height: indicatorView.frame.size.height)
        
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isPageScrolling = true
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        isPageScrolling = false
    }
}

然后在其他控制器调用即可

class MyCollectedViewController: SwipeViewController {
    override func viewDidLoad() {
      
        let articleVC: :UIViewController = UIViewController() 
        let videoVC: :UIViewController = UIViewController()
        viewControllers = [articleVC, videoVC]
        titles = ["资讯", "视频"]
        
        super.viewDidLoad()
       
    }
    

你可能感兴趣的:(Swift4.0之自定义分段控制器(SegmentedControl)的简单封装)