Swift-UIPageViewController的使用

import UIKit

class DWBTestViewController: UIViewController,UIPageViewControllerDataSource,UIPageViewControllerDelegate {
    ///懒加载一个page
    private lazy var pageViewControllerMain:UIPageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    //数组
    private lazy var dataSouceControll = [UIViewController]()
    //获取索引
    private lazy var nextIndex : Int = 0
    //创建上面的滚动条
    private lazy var scrollerView : UIScrollView = UIScrollView()
    
    //子控制器1
    private lazy var pageFirst : UIViewController = UIViewController()
    //子控制器2
    private lazy var pageTwo : UIViewController = UIViewController()
    //子控制器3
    private lazy var pageThree : UIViewController = UIViewController()
    //子控制器4
    private lazy var pagefouer : UIViewController = UIViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        //创建导航栏
       createSelfNav()
        
        //创建UI
       createPageUI()
        
    }
    
    /// 将要出现的时候影藏系统导航栏,这里创建导航栏
    func createSelfNav(){
        //导航栏父视图
        let topView = UIView()
        topView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 64)
        topView.backgroundColor = UIColor.white
        self.view.addSubview(topView)
        
        //创建返回键
        let buttonBack:UIButton = UIButton(type: .custom)
        buttonBack.frame = CGRect(x:0,y:20,width:44,height:44)
        buttonBack.setImage(UIImage(named: "返回"), for: .normal)
        buttonBack.setTitleColor(UIColor.yellow, for: .normal)
        buttonBack.addTarget(self, action:#selector(blaceAction), for: .touchUpInside)
        topView.addSubview(buttonBack)
        
        //创建标题
        let labelTitle = UILabel()
        labelTitle.frame = CGRect(x: 44, y: 20, width: SCREEN_WIDTH-88, height: 44)
        labelTitle.text = "UIPageViewController"
        labelTitle.font = UIFont.systemFont(ofSize: 18)
        labelTitle.textColor = UIColor.black
        labelTitle.textAlignment = .center
        topView.addSubview(labelTitle)
        
        
        //创建返回键
        let buttonBackRight:UIButton = UIButton(type: .custom)
        buttonBackRight.frame = CGRect(x:SCREEN_WIDTH-44,y:20,width:44,height:44)
        buttonBackRight.setImage(UIImage(named: "悬浮分享"), for: .normal)
        buttonBackRight.setTitleColor(UIColor.yellow, for: .normal)
        buttonBackRight.tag = 112222
        buttonBackRight.addTarget(self, action:#selector(blaceRightAction), for: .touchUpInside)
        topView.addSubview(buttonBackRight)
        
        
        //创建一条线
        let imageLine = UIImageView()
        imageLine.frame = CGRect(x: 0, y: 63, width: SCREEN_WIDTH, height: 1)
        imageLine.backgroundColor = UIColor.groupTableViewBackground
        topView.addSubview(imageLine)
        
        
    }
    
    //返回点击
    func blaceAction(){
        
        self.navigationController!.popViewController(animated: true)
    }
    
    //分享
    func blaceRightAction() -> Void{
        
    }
    
    
    func createPageUI() {
        
        pageViewControllerMain.view.frame = CGRect(x: 0, y: 64+33, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-64-33)
        pageViewControllerMain.delegate = self
        pageViewControllerMain.dataSource = self
        addChildViewController(pageViewControllerMain)
        view.addSubview(pageViewControllerMain.view)
        pageViewControllerMain.didMove(toParentViewController: self)
        
        //添加字控制器
        dataSouceControll += [pageFirst,pageTwo,pageThree,pagefouer]
        
//   UIPageViewControllerNavigationDirection调用了此方法切换Controller的动画可以为从左往右和从右往左两种,如果animated属性设置为NO,则这个属性无效。是枚举类型,定义了以下两种通过此方法跳转的翻页方式。     
        //从左往右(或从下往上):UIPageViewControllerNavigationDirectionForward;
        //从左往右(或从下往上): UIPageViewControllerNavigationDirectionReverse;
        //设置默认显示控制器
        pageViewControllerMain.setViewControllers([pageFirst], direction:.forward, animated: false, completion: nil)
        view.gestureRecognizers = pageViewControllerMain.gestureRecognizers
        
///MARK--创建标题栏部分
        scrollerView.frame = CGRect(x: 0, y: 64, width: SCREEN_WIDTH, height: 33)
        scrollerView.showsVerticalScrollIndicator = false
        scrollerView.showsHorizontalScrollIndicator = false
        view.addSubview(scrollerView)
        //设置滚动视图尺寸
        scrollerView.contentSize = CGSize(width: SCREEN_WIDTH, height: 33)
        
        //设置滚动标题
        let arrayTitle = ["精选","直播","美妆","美搭"]
        for i in 0..<self.dataSouceControll.count {
            let button = UIButton()
            button.frame = CGRect(x: 0.0 + SCREEN_WIDTH/CGFloat(self.dataSouceControll.count) * CGFloat(i), y: 0, width: SCREEN_WIDTH/CGFloat(self.dataSouceControll.count), height: 33)
            button.setTitle(arrayTitle[i], for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.tag = i+1
            button.setTitleColor(UIColor.black, for: .normal)
            button.setTitleColor(UIColor.red, for: .selected)
            button.addTarget(self, action: #selector(ActionButotn), for: .touchUpInside)
            scrollerView.addSubview(button)
            
            
            //标题下划线
            let imgageLine = UIImageView()
            imgageLine.frame = CGRect(x: 0.0 + SCREEN_WIDTH/CGFloat(self.dataSouceControll.count) * CGFloat(i), y: button.bottomY-2, width:SCREEN_WIDTH/CGFloat(self.dataSouceControll.count), height: 2)
            imgageLine.backgroundColor = UIColor.red
            imgageLine.tag = i+100
            imgageLine.isHidden = true
            scrollerView.addSubview(imgageLine)
            
            if i==0 {
                
                button.isSelected = true
                imgageLine.isHidden = false
            }
            
        }
    }
    
    //标题点击事件
    func ActionButotn(button:UIButton) {
        
        //找到所有buton
        for i in 0..<self.dataSouceControll.count {
            let buttonAll = view.viewWithTag(i+1) as? UIButton
            
            let imageLine = view.viewWithTag(i+100) as? UIImageView
            
            if buttonAll?.tag == button.tag {
                print(buttonAll?.tag ?? "没有找到button" )
                buttonAll?.isSelected = true
                imageLine?.isHidden = false
            }else{
                buttonAll?.isSelected = false
                 imageLine?.isHidden = true
            }
            
        }
        
        //控制器改变,设置显示控制器
        pageViewControllerMain.setViewControllers([self.dataSouceControll[button.tag-1]], direction:.forward, animated: false, completion: nil)


    }
    
///MARK---UIPageViewController代理方法--------
    //往左边滑动翻页会走此方法(类似pop回来)
//    这两个方法的使用很相似, 都是根据当前的控制器, 获取当前控制器的索引, 然后修改索引(加1或者减1)来获取下一个控制器, 并返回;
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        
        let index = self.dataSouceControll.index(of: viewController)
        
        if (index == 0) || (index == NSNotFound) {
            return nil
        }
        //守护,防止空值在解包时崩溃
        guard let index1 = index else {
            return nil
        }
         // 此处index必须减一
        return dataSouceControll[index1 - 1]
    }
    
    
     //往左边滑动翻页会走此方法(类似push下去)
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?
    {
        //获取当前控制器索引
        let index = self.dataSouceControll.index(of: viewController)
        
        if index == NSNotFound {
            return nil
        }
        
        if (index == self.dataSouceControll.count-1) {
            //防止越界,必须要设置
            return nil
        }
        //守护,防止空值在解包时崩溃
        guard let index1 = index else {
            return nil
        }
        
         return dataSouceControll[index1+1]
    }
    
//   取消pageControl,想要取消白点显示,只要不设定以下dataSource方法即可。
    func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int
    {
        return self.dataSouceControll.count
    }
    //跟页码有关
    func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int
    {
        return 0
    }
    
//    下面一个问题,就是如何获取下一个控制器的索引, 在上面两个数据源方法里无法获取准确的索引, 而应该在下面这个方法里获取:
    func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        let controller = pendingViewControllers[0]
        self.nextIndex = self.dataSouceControll.index(of: controller)!
    }
    
     //还有一个非常有用的代理,它在动画执行完毕后被调用,在controller切换完成后,我们可以在这个代理中进行一些后续操作。例如用UIPageViewController实现轮播分页等功能。
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        
        if completed {
            
            print(self.nextIndex)
            
            //找到所有buton
            for i in 0..<self.dataSouceControll.count {
                let buttonAll = view.viewWithTag(i+1) as? UIButton
                 let imageLine = view.viewWithTag(i+100) as? UIImageView
                if i == self.nextIndex {
                    buttonAll?.isSelected = true
                     imageLine?.isHidden = false
                }else{
                    buttonAll?.isSelected = false
                    imageLine?.isHidden = true
                }
                
            }

        }
                
    }
    
    
    //视图将要出现的时候执行
    override func viewWillAppear(_ animated: Bool) {
        print("将要出现")
        //影藏导航栏
        self.navigationController?.isNavigationBarHidden = true
        //影藏tabbar
        self.tabBarController?.tabBar.isHidden = true
        
        //友盟统计开始(swift)
        MobClick.beginLogPageView("\(type(of: self))")
        
    }
    //视图将要消失的时候执行
    override func viewWillDisappear(_ animated: Bool) {
        print("将要消失")
        //友盟统计结束(swift)
        MobClick.endLogPageView("\(type(of: self))")
    }
    
    //    Swift里面舍弃了OC的dealloc方法,经过笔者多方查阅资料下面方法可以替代dealloc方法
    deinit {
        
        print("走了dealloc")
    }
    


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容