欢迎使用CSDN-markdown编辑器

来源:互联网 发布:人工智能伏羲觉醒种子 编辑:程序博客网 时间:2024/06/07 03:28

动态添加控制器

需求:遇到双12等节日,要添加发红包的功能,需要将将原先tabBar控制器改为发红包的控制器。但由于app审核需要时间,以及用户必须更新才能使用红包功能造成的用户体验不佳。因此一般会提前写好这个控制器,当app请求数据时,服务器返回一个JSON文件,通过读取这个文件来改变tabBar控制器,而不是双12时则更改为普通的控制器。

知识点1:读取JSON文件

 //从服务器返回的json获取控制器字符串guard let filePath =NSBundle.mainBundle().pathForResource("VCSettings.json", ofType:nil) else{     DyLog("文件路径不存在。。。")     return}guard let data = NSData(contentsOfFile: filePath) else{      DyLog("解析服务器控制器字符串失败。。。")      return}do{    //JSON返回的数据是一个数组,数组的元素是键值对,因此要用[[String:AnyObject]]来表示这个数组    let objc = try NSJSONSerialization.JSONObjectWithData(data, options:    NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]            for item in objc{                let title = item["title"] as? String                let vcName = item["vcName"] as? String                let imageName = item["imageName"] as? String                addChildViewController(vcName, title: title, image: imageName)            }        }catch{            addChildViewController("HomeTableViewController", title: "首页", image:"tabbar_home")        }}

知识点2:从字符串创建类

    func addChildViewController(childControllerName: String?,title:String?,image:String?)->Void    {        //1,动态获取命名空间 info.plist->key->右击->property List ->None,此时的才是真正的key值        guard let namespace = NSBundle.mainBundle().infoDictionary?["CFBundleExecutable"] as? String else {            DyLog("获取命名空间失败...")            return        }        //2,根据字符串获取class        var cls:AnyClass? = nil        //先进行空值判断        if childControllerName != nil {            cls = NSClassFromString(namespace + "." + childControllerName!)        }        //3,根据类创建对象        guard let typeCls = cls as? UITableViewController.Type else {            DyLog("cls 不能作为UITableViewController")            return        }        let childController = typeCls.init()        //设置控制器属性        childController.title = title;        if image != nil        {            childController.tabBarItem.image = UIImage(named: image!)            childController.tabBarItem.selectedImage = UIImage(named:image!+"_highlighted")        }        //设置导航控制器        let vc = UINavigationController(rootViewController:childController)        addChildViewController(vc)    }

知识点3:自定义Log

 //print(#file)  打印所在的方法 //print(#function)  打印所在的行 //print(#line)   打印所在文件的路径 方法名称[行数]: 输出内容 需要在weibo->targets->build setting->搜索custom flag ->在debug加上-D DEBUG */func DyLog<T>(message:T,file:String = #file,function:String = #function,line:Int = #line){    #if DEBUG        print("\((file as NSString).lastPathComponent) \(function)[\(line)]:\(message)")    #endif}

注:仅为个人笔记,涉及侵权请联系

0 0
原创粉丝点击