简单的swift分段控制器

首先需要倒入一个第三方文件PageTitleView
然后去Appdelegate里面设置一下导航栏

let vc = ViewController()
        
        let nav = UINavigationController(rootViewController: vc)
        
        self.window?.rootViewController = nav
        return true

然后我们在view Didload上面写点方法

private lazy var pageTitleView: MFPageTitleView = {
        let config = MFPageTitleViewConfig()
        config.titleColor = colorWithRGB(r: 43, g: 43, b: 43)
        config.titleSelectedColor = colorWithRGB(r: 211, g: 0, b: 0)
        config.titleFont = UIFont.systemFont(ofSize: 14, weight: .regular)
        config.indicatorColor = colorWithRGB(r: 211, g: 0, b: 0)
        let pageTitleView = MFPageTitleView(frame: CGRect(x: 0, y: navHeight, width: SCREEN_WIDTH, height: 41), titles: ["推荐", "深度", "快讯", "实时对话", "科技", "行情分析"], config: config)
        pageTitleView.pageTitleViewDelegate = self as MFPageTitleViewDelegate
        return pageTitleView
    }()

继续我们的代码
private lazy var pageContentView: MFPageContentView = { var childControllers = [OneVc(),TwoVc(),ThreeVc(),OneVc(),TwoVc(),ThreeVc()] for var k in 0..<6 { var vc = childControllers[k] // if(0==k){ // vc = OneVC() // } let red: CGFloat = CGFloat(arc4random() % 256) let green: CGFloat = CGFloat(arc4random() % 256) let blue: CGFloat = CGFloat(arc4random() % 256) vc.view.backgroundColor = UIColor(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: 1.0) // childControllers.append(vc) }
然后我们来确定一下分段控制器的位置

let pageContentViewY = pageTitleView.frame.maxY
        let pageContentView = MFPageContentView(frame: CGRect(x: 0, y: pageContentViewY, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-pageContentViewY), parentVC: self, childVCs: childControllers)
        pageContentView.pageContentViewDelegate = self
        return pageContentView
    }()

接下来是在view DidLoad里面完成

view.backgroundColor = UIColor.white
        view.addSubview(pageTitleView)
        view.addSubview(pageContentView)

最后写一个拓展方法,这个是在最外面写的,完成我们简单的分段控制器

extension ViewController: MFPageTitleViewDelegate, MFPageContentViewDelegate {
    func selectedIndexInPageTitleView(pageTitleView: MFPageTitleView, selectedIndex: Int) {
        self.pageContentView.setPageContentViewCurrentIndex(currentIndex: selectedIndex)
    }
    func pageContentViewScroll(progress: CGFloat, originalIndex: Int, targetIndex: Int) {
        self.pageTitleView.setPageTitleView(progress: progress, originalIndex: originalIndex, targetIndex: targetIndex)
    }
}

你可能感兴趣的:(简单的swift分段控制器)