欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Swift - 使用UITabBarController UINavigationcontroller搭建项目

程序员文章站 2022-04-01 12:42:10
...

首先记得在AppDelegate指定rootViewController

        window = UIWindow (frame: UIScreen.main.bounds)
        window?.rootViewController = TabbarController()
        window?.makeKeyAndVisible()

然后在TabbarController里写入下面两个方法并使用就好

    private func addChildViewController() {
        addChildViewController(controller: HomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(controller: MessageViewController(), title: "消息", imageName: "tabbar_message")
        addChildViewController(controller: DiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(controller: MeViewController(), title: "我", imageName: "tabbar_me")
    }
    
    private func addChildViewController(controller:UIViewController, title:String,imageName:String) {
        controller.tabBarItem.image = UIImage(named: imageName)
        controller.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")
        controller.tabBarItem.title = title
        
        let nav = NavigationController()
        nav.addChildViewController(controller)
        addChildViewController(nav)
    }

创建NavigationController,在这里我们可以对导航栏做一些默认配置,比如字体,颜色,大小什么的,而且在这里去自定义左侧返回按钮比较方便

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.interactivePopGestureRecognizer!.delegate = nil;
        
        let appearance = UINavigationBar.appearance()
        appearance.isTranslucent = false
        
        appearance.setBackgroundImage(UIImage.imageWithColor(color: Color_NavBackground, size: CGSize(width: 1, height: 1)), for: UIBarMetrics.default)
        
        var textAttrs:[String:AnyObject] = Dictionary()
        textAttrs[NSForegroundColorAttributeName] = UIColor.white
        textAttrs[NSFontAttributeName] = UIFont.systemFont(ofSize: 16)
        
        appearance.titleTextAttributes = textAttrs
        
    }

这样一个项目的基本框架就算搭建完成了,四个主页面建议继承一个BaseViewController,方便我们做一些公共部署。