博客> swift3.0 自定义TabBar
swift3.0 自定义TabBar
2017-12-14 00:49 评论:0 阅读:662 1498893132
ios tabbar Xcode8 swift3.0

首先创建一个属于自己的tabbar类TabBarViewController.swift ,同时再创建一个自己的导航栏NavigationViewController_design.swift,用于统一定义自己的导航栏样式

一、在AppDelegate.swift 所要书写的代码在 didFinishLaunchingWithOptions方法中

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    let tabBarVC = TabBarViewController()

    self.window?.rootViewController = tabBarVC

    //UINavigationController.init(rootViewController: tabBarVC)

// self.window?.makeKeyAndVisible()

    return true
}

二、在创建的类TabBarViewController.swift中书写的代码为

import UIKit

class TabBarViewController: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor = UIColor.white

    addChildViewControllers()
}

func addChildViewControllers() {
    let firstVC = FirstViewController()
    addChildViewController(firstVC, title: "城市服务", imageName: "tab_1", imageSelectName: "tab_1_ed", tag: 0)
    let secondVC = SecondViewController()
    addChildViewController(secondVC, title: "特约商户", imageName: "tab_2", imageSelectName: "tab_2_ed", tag: 0)

    let thirdVC = ThirdViewController()
    addChildViewController(thirdVC, title: "我的", imageName: "tab_3", imageSelectName: "tab_3_ed", tag: 0)
}

func addChildViewController(_ childController: UIViewController, title:String, imageName:String , imageSelectName:String,tag: Int) {

// let namesspace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String //
// let cls:AnyClass = NSClassFromString(namesspace + "." + childController)! //
// let vcCls = cls as! UIViewController.Type //
let vc = childController vc.title = title //同时设置tabbar和navigationBar的文字

    tabBar.tintColor = UIColor.orange
    vc.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0)
    vc.tabBarItem.image = UIImage(named: imageName)
    vc.tabBarItem.selectedImage = UIImage(named: imageSelectName)
    vc.tabBarItem.tag = tag

    let nav = NavigationViewController_design.init(rootViewController: vc)
    self.addChildViewController(nav)
}

}

三、在创建的导航栏类NavigationViewController_design.swift中 代码如下 import UIKit

class NavigationViewController_design: UINavigationController {

override class func initialize() {

    let navBar = UINavigationBar.appearance()

    let navigationTitleAttribute: NSDictionary = [NSForegroundColorAttributeName:UIColor.black,NSFontAttributeName: UIFont.systemFont(ofSize: 20)];
    navBar.titleTextAttributes = navigationTitleAttribute as? [String : AnyObject]

}

override func viewDidLoad() {
    super.viewDidLoad()
}

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

}

四、根据需要创建需要的控制器类 比如:FirstViewController,SecondViewController,ThirdViewController

收藏
1
sina weixin mail 回到顶部