美文网首页Swift项目开发之功能模块
(Swift)基础项目搭建(导航栏UITabbarControl

(Swift)基础项目搭建(导航栏UITabbarControl

作者: MangoJ | 来源:发表于2017-02-21 14:28 被阅读105次

    第一讲开始!

    万事开头难,项目结构框架搭建是整个APP开发的头,是核心,是地基,只有结构搭建完成才能继续后面的工作,所以这第一讲毫无疑问必须要介绍项目的搭建,当然本文仅是基础搭建,正如标题所示是对导航栏UITabbarController及标签栏UINavigationController的创建,虽然基础但也非常重要.
    下面👇为代码详情
    首先,看一下项目的目录结构


    MyProject.png

    首先创建文件MainViewController继承UITabbarController, MyNavViewController继承UINavigationController,MyBaseViewController继承UIViewController,还要创建HomePageViewController, MessageViewController, DiscoverViewController, ProfileViewController都继承

    接下来,在AppDelegate中创建window并设置跟视图

     import UIKit
    
      @UIApplicationMain
     class AppDelegate: UIResponder, UIApplicationDelegate {
    
      var window: UIWindow?
    
     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //设置全局颜色
        UITabBar.appearance().tintColor = UIColor.black
        //创建 window
        window = UIWindow(frame: UIScreen.main.bounds)
        //设置跟控制器为MainViewController
        window?.rootViewController = MainViewController()
        window?.makeKeyAndVisible()
    
        return true
      }
    }
    

    然后,一两种方案创建Tabbar,代码中有详细的介绍

    import UIKit
    
    class MainViewController: UITabBarController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //查看方案1效果
            //        setupChildController()
            //查看方案2效果
            setupChildViewCotroller()
        }
        //portrait 竖屏
        //landscape 横屏
        //多数情况下我们使用的是竖屏  播放视频时可用modal实现
        override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
            return.portrait
        }
    
        //MARK:方案1
        //设置所有控制器
        func setupChildController()  {
    
            addChildViewController(HomePageViewController(), title: "首页", imageName: "tabbar_home")
            addChildViewController(MessageViewController(), title: "消息", imageName: "tabbar_home")
            addChildViewController(DiscoverViewController(), title: "发现", imageName: "tabbar_home")
            addChildViewController(ProfileViewController(), title: "我的", imageName: "tabbar_home")
    
        }
        //重载下列方法
        /** 方法的重载:方法名称相同,但是参数不同. --> 1.参数的类型不同 2.参数的个数不同
         private在当前文件中可以访问,但是其他文件不能访问
         */
        private func addChildViewController(_ childController: UIViewController,title : String, imageName : String) {
            // 1.设置子控制器的属性
            childController.title = title
            childController.tabBarItem.image = UIImage(named: imageName)
            childController.tabBarItem.selectedImage = UIImage(named: imageName+"_highlighted")
            //2.设置导航栏控制器
            let childNaVc  = MyNavViewController(rootViewController: childController)
            addChildViewController(childNaVc)
    
        }
    
        //MARK:方案2
        func setupChildViewCotroller()  {
            let array = [
                ["clsName":"HomePageViewController","title":"首页","imageName":"home"],
                ["clsName":"MessageViewController","title":"消息","imageName":"home"],
                ["clsName":"DiscoverViewController","title":"发现","imageName":"home"],
                ["clsName":"ProfileViewController","title":"我的","imageName":"home"]
            ]
            var arrayM = [UIViewController]()
            for dict in array {
                arrayM.append(controllers(dict: dict))
            }
    
            viewControllers = arrayM
    
        }
    
        /// 使用字典创建一个子控制器
        ///
        /// - parameter dict: 信息字典[clsName,title,imageName]
        /// - returns 子控制器
    
        private func controllers(dict:[String:String])->UIViewController{
            //1.取得字典内容
            //获取命名空间
            let bundleName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
            /**
             let cls = NSClassFromString(bundleName + "." + clsName) as? UIViewController.Type
             根据字符串获取对应的Class并将对应的AnyObject转成控制器的类型
                */
            guard let clsName = dict["clsName"],let title = dict["title"],let imageName = dict["imageName"],let cls = NSClassFromString(bundleName + "." + clsName) as? UIViewController.Type else {
                return UIViewController()
            }
            //2.创建视图控制器
            let vc = cls.init()
            vc.title = title
            let  nav = MyNavViewController(rootViewController: vc)
            //3.设置tabbar 图像
            vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
            //withRenderingMode(.alwaysOriginal)颜色渲染
            vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_highlighted")?.withRenderingMode(.alwaysOriginal)
            //4.设置tabbar的标题字体颜色(如果不设置图片字体颜色无效果)
            vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
            vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
            return nav
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    }
    

    接着我们在MyBaseViewController中做一些设置,项目中很多控制器都是继承这个BaseViewControlle,以继承其内部的一些共用的属性或方法(本文中为自定义NavigationBar)
    代码如下👇

    import UIKit
    
    class MyBaseViewController: UIViewController {
    //自定义导航条
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64))
    //自定义导航条目 - 之后设置导航条内容 统一用 navItem
    lazy var navItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        // Do any additional setup after loading the view.
    }
    
    //重写title的didSet方法
    override var title: String?{
        didSet{
            navItem.title = title
        }
    }
    
    //设置导航条
    private func setupNavigationBar(){
        //添加导航条
        view.addSubview(navigationBar)
        //将item条目设置到Bar上
        navigationBar.items = [navItem]
        //设置navBar的渲染颜色
        navigationBar.barTintColor = UIColor.orange
        //设置字体的颜色
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
        //设置系统按钮文字的渲染颜色
        navigationBar.tintColor = UIColor.white
      }
    }
    

    最后是对NavigationItem的处理,在MyNavViewController中

    import UIKit
    
    class MyNavViewController: UINavigationController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //隐藏navgationBar(如果需要要重写navigationBar)
      //        navigationBar.isHidden = true
        // Do any additional setup after loading the view.
    }
    
    
     override func pushViewController(_ viewController: UIViewController, animated: Bool) {
         //如果不是栈底控制器才会隐藏
        if childViewControllers.count>0 {
            viewController.hidesBottomBarWhenPushed = true
            //判断控制器的级数
            if childViewControllers.count == 1 {
                //级数为1时显示的是首页的标题否则显示 "返回"
                title = childViewControllers.first?.title ?? "返回"
    
            }else{
                title = "返回"
            }
            viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(title: title, style: .done, target: self, action: #selector(popback))
    
        }
        super.pushViewController(viewController, animated: true)
    }
    
    //返回上一级
    @objc private func popback(){
        popViewController(animated: true)
      }
    }
    

    基本的结构框架搭建到这里就结束,相信对读者朋友会有所帮助,如果觉得文章还可以,点击下方👇喜欢鼓励一下,没关注的朋友可以点击一下关注,专题系列讲解持续更新中!
    专题目录:Swift开发之功能模块

    相关文章

      网友评论

        本文标题:(Swift)基础项目搭建(导航栏UITabbarControl

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