美文网首页
多界面开发

多界面开发

作者: d5cbd4f07363 | 来源:发表于2019-02-01 14:19 被阅读5次

    多界面开发 顶部滑动标签使用UICollectionView ,界面使用UIPageviewController控制器

    //

    //  YLJSpecialViewController.swift

    //  ShopNC B2B2C

    //

    //  Created by 鱼老九 on 2019/1/30.

    //  Copyright © 2019年 ShopNC. All rights reserved.

    //

    /**

     专题模版

     */

    import UIKit

    importSnapKit

    importAlamofire

    importSwiftyJSON

    classYLJNavSpecialDataFrame:NSObject{

        vartitle :String!

        varisHiddenLine :Bool=true

        vartitleFrame :CGRect!

    }

    class YLJSpecialViewController: UIViewController,UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIPageViewControllerDelegate,UIPageViewControllerDataSource{

        lettitles =  ["查看0","管理理1","优化优化2","收藏收藏藏3","管理管理管理4","管理管理管理管5","收藏管理管理管理管理6","收藏收藏藏7","管理管理管理8","收藏收藏藏9","管理管理管理10","收藏收藏藏11","管理管理管理12"]

        var navspecialFrames : Array<YLJNavSpecialDataFrame> = Array<YLJNavSpecialDataFrame>()

        letUICollectionViewCellID ="UICollectionViewCellID"

        let screenWidth : CGFloat = UIScreen.main.bounds.size.width

        let screenHeight : CGFloat = UIScreen.main.bounds.size.height

        varnavSelectedindexPath :IndexPath?//被选中的cell的indexpatch

        let pageViewController : UIPageViewController = UIPageViewController.init(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal, options: nil)

        var ArrayVc : Array<UIViewController> = Array<UIViewController>()//子控制器数组

        varcollectionView :UICollectionView!//导航条标签

        varcurrentVCIndex :Int!//当前控制器索引

        overridefuncviewDidLoad() {

            super.viewDidLoad()

            for(key,item)intitles.enumerated() {

                letnavSpecialdataFrame =YLJNavSpecialDataFrame()

                navSpecialdataFrame.title= item

               // 标题的frame

                letfont:UIFont! =UIFont.systemFont(ofSize:CGFloat(10*ScreenMultiple))

                letattributes1 = [NSFontAttributeName:font]as[String:Any]

                let option = NSStringDrawingOptions.usesLineFragmentOrigin

                letsize = item.boundingRect(with:CGSize(width:screenWidth, height:500), options: option, attributes: attributes1, context:nil).size

                 navSpecialdataFrame.titleFrame=CGRect(x:0, y:0, width:CGFloat(size.width) +CGFloat(10*ScreenMultiple), height:44)

                //是否显示横线

                ifkey ==0{

                    navSpecialdataFrame.isHiddenLine=false

                }

                navspecialFrames.append(navSpecialdataFrame)

                letVc =UIViewController.init()

                letlabel =UILabel()

                label.textColor=UIColor.black

                label.textAlignment= .center

                label.text=String(key)

                label.frame=CGRect(x:0, y:100, width:screenWidth, height:300)

                Vc.view.addSubview(label)

                ifkey%2==0{

                    Vc.view.backgroundColor = UIColor.white

                }else{

                    Vc.view.backgroundColor = UIColor.green

                }

                self.ArrayVc.append(Vc)

            }

            let flowLayout = UICollectionViewFlowLayout()

            flowLayout.scrollDirection= .horizontal

            flowLayout.minimumInteritemSpacing = 10;

             collectionView=UICollectionView(frame:CGRect(x:0, y:0, width:screenWidth, height:44), collectionViewLayout: flowLayout)

            collectionView.showsVerticalScrollIndicator = false

            collectionView.showsHorizontalScrollIndicator = false

            collectionView.delegate = self

            collectionView.dataSource = self

            collectionView.backgroundColor = UIColor.white

            collectionView.register(YLJNavSpecialCell.self, forCellWithReuseIdentifier: UICollectionViewCellID)

            self.navigationItem.titleView = collectionView

            //单个视图控制器多个标签页切换使用

            pageViewController.delegate = self

            pageViewController.dataSource = self

            self.addChildViewController(pageViewController)

            self.view.addSubview(pageViewController.view)

            ifISIPHONEX{

                pageViewController.view.frame=CGRect(x:0, y:0, width:screenWidth, height:screenHeight-83)

            }else{

                pageViewController.view.frame=CGRect(x:0, y:0, width:screenWidth, height:screenHeight  -49)

            }

            self.pageViewController.setViewControllers([self.ArrayVc[0]], direction:UIPageViewControllerNavigationDirection.forward, animated:true, completion:nil)

            //http://192.168.0.133/mobile/index.php?act=index&op=get_special

            let url = "\(API_URL)index.php?act=index&op=get_special"

    //        Alamofire.request(url).response(queue: DispatchQueue.global()) { (returnResult) in

    //            if  let data = returnResult.data {

    //                let json = JSON.init(data)

    //                print("专题数据:",json)

    //                var imgUrls : Array = Array()

    //                for (key,item) in json["datas"].arrayValue.enumerated() {

    //                    //special_title

    //                    let specialDataFrame = YLJNavSpecialDataFrame()

    //                    specialDataFrame.title = item["special_title"].stringValue

    //                    let font:UIFont! = UIFont.systemFont(ofSize: CGFloat(10*ScreenMultiple))

    //                    let attributes1 = [NSFontAttributeName:font] as [String : Any]

    //                    let option = NSStringDrawingOptions.usesLineFragmentOrigin

    //                    let size = item["special_title"].stringValue.boundingRect(with: CGSize(width: self.screenWidth, height: 500), options: option, attributes: attributes1, context: nil).size

    //                    specialDataFrame.titleFrame = CGRect(x: 0, y: 0, width: CGFloat(size.width) + CGFloat(10*ScreenMultiple), height: 44)

    //                    //是否显示横线

    //                    if key == 0 {

    //                        specialDataFrame.isHiddenLine = false

    //                    }

    //

    //                    //let jsons = JSON.init(item["special_content"].string)

    //

    //                    //print("专题图片信息:",)

    //                    var array = Array()

    //                    for j in JSON.init(parseJSON: item["special_content"].stringValue)["app"]["img"] .arrayValue {

    //                      print("专题图片信息:",j)

    //                        let urlinfo = YLJImagsUrl()

    //                        urlinfo.url = j["src"].stringValue

    //                        urlinfo.goods_id = j["id"].stringValue

    //                        array.append(urlinfo)

    //                    }

    //                    imgUrls.append(array)

    //                    self.navspecialFrames.append(specialDataFrame)

    //                }

    //                DispatchQueue.main.async {

    //

    //                    for key in 0 ..< self.navspecialFrames.count {

    //                        let subVC = YLJSpecialSubOneViewController()

    //                        subVC.url_strs = imgUrls[key] as! Array

    //

    //                        self.ArrayVc.append(subVC)

    //                    }

    //                    self.collectionView.reloadData()

    //                    if self.ArrayVc.count > 0 {

    //                        self.pageViewController.setViewControllers([self.ArrayVc[0]], direction: UIPageViewControllerNavigationDirection.forward, animated: true, completion: nil)

    //                    }

    //                }

    //            }

    //        }

        }

        funccollectionView(_collectionView:UICollectionView, numberOfItemsInSection section:Int) ->Int{

            return self.navspecialFrames.count

        }

        funccollectionView(_collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) ->UICollectionViewCell{

            letcell = collectionView.dequeueReusableCell(withReuseIdentifier:UICollectionViewCellID, for: indexPath)as!YLJNavSpecialCell

            //cell.backgroundColor = UIColor.white

            cell.titleLabel.text = navspecialFrames[indexPath.item].title

            cell.lineLabel.isHidden = navspecialFrames[indexPath.item].isHiddenLine

            ifself.navSelectedindexPath==nil&& indexPath.item==0{

                self.navSelectedindexPath= indexPath

            }

            returncell

        }

        funccollectionView(_collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) ->CGSize{

            return navspecialFrames[indexPath.item].titleFrame.size

        }

        funccollectionView(_collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) {

            print("点击了第几个cell",indexPath.item)

            //对选中的indexpath 的cell 进行恢复

            letcell = collectionView.cellForItem(at:self.navSelectedindexPath!)as?YLJNavSpecialCell

            cell?.lineLabel.isHidden=true

            //对数据进行恢复

            let dataFrame = self.navspecialFrames[(self.navSelectedindexPath?.item)!]

            dataFrame.isHiddenLine=true

            //对当前选中的cell界面进行更新

            letcurrentCell = collectionView.cellForItem(at: indexPath)as?YLJNavSpecialCell

            currentCell?.lineLabel.isHidden=false

            //对数据进行刷新

            letcurrentDataFrame =self.navspecialFrames[indexPath.item]

            currentDataFrame.isHiddenLine=false

            // self.pageViewController

            //对pageviewcontroller进行设置

            letisDirection = (self.navSelectedindexPath?.item)! > indexPath.item?1:0

            pageViewController.setViewControllers([ArrayVc[indexPath.item]], direction: isDirection ==1?  UIPageViewControllerNavigationDirection.reverse:UIPageViewControllerNavigationDirection.forward, animated:true, completion:nil)

            self.navSelectedindexPath= indexPath

        }

        //MARK:UIPageViewControllerDelegate

        funcpageViewController(_pageViewController:UIPageViewController, didFinishAnimating finished:Bool, previousViewControllers: [UIViewController], transitionCompleted completed:Bool) {

            ifcompleted {

                ifcurrentVCIndex!=ArrayVc.index(of: previousViewControllers[0]) {

                 print("当前控制器索引",currentVCIndex)

                    collectionView.scrollToItem(at:IndexPath(item:currentVCIndex!, section:0), at:UICollectionViewScrollPosition.centeredHorizontally, animated:true)

                    collectionView(collectionView, didSelectItemAt:IndexPath(item:currentVCIndex, section:0))

                }

            }

        }

        funcpageViewController(_pageViewController:UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {

            currentVCIndex=ArrayVc.index(of: pendingViewControllers[0])

        }

        //MARK:UIPageViewControllerDataSource

        funcpageViewController(_pageViewController:UIPageViewController, viewControllerBefore viewController:UIViewController) ->UIViewController? {

            guardletviewControllerIndex =ArrayVc.index(of: viewController)else{

                returnnil

            }

            letpreviousIndex = viewControllerIndex -1

            guardpreviousIndex >=0else{

                returnnil

            }

            guardArrayVc.count> previousIndexelse{

                returnnil

            }

            returnArrayVc[previousIndex]

        }

        funcpageViewController(_pageViewController:UIPageViewController,viewControllerAfter viewController:UIViewController) ->UIViewController? {

            guardletviewControllerIndex =ArrayVc.index(of: viewController)else{

                returnnil

            }

            letnextIndex = viewControllerIndex +1

            letorderedViewControllersCount =ArrayVc.count

            guardorderedViewControllersCount != nextIndexelse{

                returnnil

            }

            guardorderedViewControllersCount > nextIndexelse{

                returnnil

            }

            returnArrayVc[nextIndex]

    }

        overridefuncdidReceiveMemoryWarning() {

            super.didReceiveMemoryWarning()

            // Dispose of any resources that can be recreated.

        }

        overridefuncviewWillAppear(_animated:Bool) {

            super.viewWillAppear(animated)

            self.navigationController?.navigationBar.barTintColor = NAVI_BAR_COLOR

            self.navigationController?.navigationBar.isTranslucent = false

            // self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)

            self.navigationController?.navigationBar.barStyle = UIBarStyle.default

    //        self.navigationController?.navigationBar.isHidden = true

            self.tabBarController?.tabBar.tintColor=UIColor(red:255/255, green:80/255, blue:57/255, alpha:1.0)

            self.navigationController?.tabBarItem.selectedImage = self.navigationController?.tabBarItem.selectedImage?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)

        }

        overridefuncviewWillDisappear(_animated:Bool) {

            super.viewWillDisappear(animated)

        }

    }

    相关文章

      网友评论

          本文标题:多界面开发

          本文链接:https://www.haomeiwen.com/subject/yhkdsqtx.html