如何通过字符串创建类 动态获取命名空间

//
//  DSTabBarController.swift
//  DSWeibo
//
//  Created by 刘小二 on 16/5/22.
//  Copyright © 2016年 刘小二. All rights reserved.
//

import UIKit

class DSTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
    
        addchildViewControllers()
        
    }
    
    
   private func addchildViewControllers()
    {
        
        // 设置全局的文字图片的选中颜色
        tabBar.tintColor = UIColor.orangeColor()
        
        // 添加子控制器
//        let home = HomeViewController()
//        addChildViewController(childController:home, title: "首页", image: "tabbar_home", selectedImage: "tabbar_home" + "highlighted")
//        let discover = DicoverViewController()
//        addChildViewController(childController:discover, title: "发现", image: "tabbar_discover", selectedImage: "tabbar_discover" + "highlighted")
//        let message = MessageViewController()
//        addChildViewController(childController:message, title: "消息", image: "tabbar_message_center", selectedImage: "tabbar_message_center" + "highlighted")
//        let mine = MineViewController()
//        addChildViewController(childController: mine, title: "我的", image: "tabbar_profile", selectedImage: "tabbar_profile" + "highlighted")
        
        
        // 使用字符串创建对应的类
        addChildViewController(childController: "HomeViewController", title: "首页", image: "tabbar_home", selectedImage: "tabbar_home" + "highlighted")
        addChildViewController(childController: "DicoverViewController", title: "发现", image: "tabbar_discover", selectedImage: "tabbar_discover" + "highlighted" )
        addChildViewController(childController: "MessageViewController", title: "消息", image: "tabbar_message_center", selectedImage: "tabbar_message_center" + "highlighted" )
        addChildViewController(childController: "MineViewController", title: "我的", image: "tabbar_profile", selectedImage: "tabbar_profile" + "highlighted" )
    }

    
}


extension DSTabBarController
{
    // MARK: - 添加子控制器的方法
    func addChildViewController(childController childController: String , title: String , image : String , selectedImage : String) {
        
        // 得到命名空间
        
        let mm = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        
        
        let vcc:AnyClass? = NSClassFromString(mm + "." + childController)
        let vc = vcc as! UIViewController.Type
        
        let oc = vc.init()
        
        oc.tabBarItem.title = title
        oc.tabBarItem.image = UIImage(named:image)
        oc.tabBarItem.selectedImage = UIImage(named: selectedImage)
        let nav = DSNavigationController(rootViewController:oc)
        addChildViewController(nav)
    }

    
}

你可能感兴趣的:(如何通过字符串创建类 动态获取命名空间)