UI框架快速套用(NavigationController+TabBar)

标题实在有够醒目的了
这几天开始在做实际的项目,也参考了好多框架,但都过于复杂,代码看得头晕,还是简书上的XMTV(熊猫TV的作者:http://www.jianshu.com/u/66a861134217)
弄的框架一目了然,而且代码逻辑清晰,于是单独把框架移过来到自己项目使用了,在此,贴上代码,供新手们观看,我也是借花献佛!

先来两张图

BBB1344E-5062-426B-9A38-E0B1332830AC.png
5551056E-A8C4-4980-8EB2-98C91B0CF429.png
//
//  Common.swift
//  AppFrameworks
//
//  Created by apiapia on 3/8/17.
//  Copyright © 2017 apiapia. All rights reserved.
//

import Foundation

import UIKit
/// 归档路径
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
let SELECTED_CHANNELS: String = "selectedChannels.archive" // 选择频道列表
let UNSELECTED_CHANNELS: String = "unselectedChannels.archive" // 未选择频道列表
let PAGE_TITLES: String = "pagetitles.archive" // 保存的pagetitles
let HOME_CHILDVCS: String = "childvcs" // 首页contentView中的子控制器
let DEFAULT_CHILDVCS: String = "default" // 首页初始化的子控制器
let ALL_GMES: String = "GameVC.archive"

/// notification
let NotifyUpdateCategory = NSNotification.Name(rawValue:"notifyUpdateCategory")
let KSelectedChannel: String = "selectedChannel"
/// 常用属性
let kItemMargin : CGFloat = 10
let kHeaderViewH : CGFloat = 50
let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2
let kNormalItemH = kNormalItemW * 3 / 4
let NormalCellID = "NormalCellID"
let SearchCellID = "SearchCellID"
let HeaderViewID = "HeaderViewID"

let kStatusBarH: CGFloat = 20
let kNavigationBarH: CGFloat = 44
let kTabBarH: CGFloat = 49
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
let BGCOLOR: UIColor = UIColor(gray: 244)
/// 初始化common
let common = Common()

class Common: NSObject {
    // MARK: -  创建一个barButtonItem
    class func itemWithImage(_ image:UIImage,highlightImage:UIImage,target:UIViewController,action:Selector) -> UIBarButtonItem{
        let button = UIButton.init()
        button.setBackgroundImage(image, for: UIControlState())
        button.setBackgroundImage(highlightImage, for: .highlighted)
        button.sizeToFit()
        button.addTarget(target, action: action, for: .touchUpInside)
        return UIBarButtonItem.init(customView: button)
    }
    
    // MARK: -解档归档(保存的是GameModel数组)
    // 归档
    func archiveData(channel: [GameModel], appendPath: String) {
        let filePath = path.appendingPathComponent(appendPath)
        NSKeyedArchiver.archiveRootObject(channel, toFile: filePath)
    }
    
    //反归档
    func unarchiveData(appendPath: String) -> ([GameModel]?) {
        let filePath = path.appendingPathComponent(appendPath)
        return NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [GameModel]
    }
    
    // MARK: -解档归档(保存的是String数组)
    // 归档
    func archiveWithStringArray(channel: [String], appendPath: String) {
        let filePath = path.appendingPathComponent(appendPath)
        NSKeyedArchiver.archiveRootObject(channel, toFile: filePath)
    }
    
    //反归档
    func unarchiveToStringArray(appendPath: String) -> ([String]?) {
        let filePath = path.appendingPathComponent(appendPath)
        return NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [String]
    }
    
    ///
    func archive(array: [AnyObject], appendPath: String) {
        let filePath = path.appendingPathComponent(appendPath)
        NSKeyedArchiver.archiveRootObject(array, toFile: filePath)
    }
    
    func unarchive(appendPath: String) -> ([AnyObject]?) {
        let filePath = path.appendingPathComponent(appendPath)
        return NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! ([AnyObject]?)
    }
}

//
//  UIColor+Extension.swift
//  AppFrameworks
//
//  Created by apiapia on 3/8/17.
//  Copyright © 2017 apiapia. All rights reserved.
//
import UIKit

extension UIColor {
    /// rgb颜色
    convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
        self.init(red: r/255.0 ,green: g/255.0 ,blue: b/255.0 ,alpha:1.0)
    }
    /// 纯色(用于灰色)
    convenience init(gray: CGFloat) {
        self.init(red: gray/255.0 ,green: gray/255.0 ,blue: gray/255.0 ,alpha:1.0)
    }
    
    class func randomColor() -> UIColor {
        return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
    }
}

//
//  AppDelegate.swift
//  AppFrameworks
//
//  Created by apiapia on 3/8/17.
//  Copyright © 2017 apiapia. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        window = UIWindow.init()
        let tabBarController = TabBarController.init()
        window?.rootViewController = tabBarController
        window?.makeKeyAndVisible()
        
        // 显示引导页         
         
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}


//
//  TabBarController.swift
//  AppFrameworks
//
//  Created by apiapia on 3/8/17.
//  Copyright © 2017 apiapia. All rights reserved.
//

import UIKit

class TabBarController: UITabBarController {
        
        override class func initialize() {
            var attrs = [String: NSObject]()
            attrs[NSForegroundColorAttributeName] = UIColor(r: 87, g: 206, b: 138)
            // 设置tabBar字体颜色
            UITabBarItem.appearance().setTitleTextAttributes(attrs, for:.selected)
        }
        
        // MARK: - life cycle
        override func viewDidLoad() {
            super.viewDidLoad()
            addAllChildViewControllers()
            let backView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 49))
            backView.backgroundColor = UIColor.white
            tabBar.insertSubview(backView, at: 0)
            tabBar.isOpaque = true
        }
        
        // MARK: - private method
        /// 添加所有子控制器
        func addAllChildViewControllers() {
            
            setupOneChildViewController("首页", image: "menu_homepage_nor", selectedImage: "menu_homepage_sel", controller: HomeVC.init())
            setupOneChildViewController("游戏", image: "menu_youxi_nor", selectedImage: "menu_youxi_sel", controller: GameVC.init())
            setupOneChildViewController("娱乐", image: "menu_yule_nor", selectedImage: "menu_yule_sel", controller: EntertainmentVC.init())
            setupOneChildViewController("小葱秀", image: "menu_goddess_nor", selectedImage: "menu_goddess_sel", controller: SmallShowVC.init())
            // 记得删除掉Info.plist Main storyboard file base name
            setupOneChildViewController("我的", image: "menu_mine_nor", selectedImage: "menu_mine_sel", controller: UIStoryboard(name: "MySB", bundle: nil).instantiateInitialViewController()!)
            
        }
        
        /// 添加一个子控制器
        fileprivate func setupOneChildViewController(_ title: String, image: String, selectedImage: String, controller: UIViewController) {
            
            controller.tabBarItem.title = title
            controller.title = title
            controller.view.backgroundColor = BGCOLOR
            controller.tabBarItem.image = UIImage(named: image)
            controller.tabBarItem.selectedImage = UIImage(named: selectedImage)
            
            let naviController = NavigationController.init(rootViewController: controller)
            self.addChildViewController(naviController)
        }
        
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        
}

//
//  NavigationController.swift
//  AppFrameworks
//
//  Created by apiapia on 3/8/17.
//  Copyright © 2017 apiapia. All rights reserved.
//


import UIKit

class NavigationController: UINavigationController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // UINavigationBar.appearance().barTintColor = UIColor.white
        // 设置naviBar背景图片
        UINavigationBar.appearance().setBackgroundImage(UIImage.init(named: "navigationbarBackgroundWhite"), for: UIBarMetrics.default)
        // 设置title的字体
        // UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName:UIFont.systemFont(ofSize: 20)]
        self.interactivePopGestureRecognizer?.delegate = nil
    }
    
    // MARK: - 拦截push控制器
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
      
        print("拦截push控制器",self.viewControllers.count)
        
        if self.viewControllers.count < 1 {
            viewController.navigationItem.rightBarButtonItem = setRightButton()
            
        } else {
            viewController.hidesBottomBarWhenPushed = true
            viewController.navigationItem.leftBarButtonItem = setBackBarButtonItem()
        }
        super.pushViewController(viewController, animated: true)
    }
    
    
    // MARK: - private method
    func setBackBarButtonItem() -> UIBarButtonItem {
        
        let backButton = UIButton.init(type: .custom)
        backButton.setImage(UIImage(named: "setting_back"), for: .normal)
        backButton.sizeToFit()
        backButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)
        backButton.addTarget(self, action: #selector(NavigationController.backClick), for: .touchUpInside)
        return UIBarButtonItem.init(customView: backButton)
    }
    
    /// 设置导航栏右边按钮
    func setRightButton() -> UIBarButtonItem {
        
        let searchItem = UIButton.init(type: .custom)
        searchItem.setImage(UIImage(named: "searchbutton_nor"), for: .normal)
        searchItem.sizeToFit()
        searchItem.frame.size = CGSize(width: 30, height: 30)
        searchItem.contentHorizontalAlignment = .right
        searchItem.addTarget(self, action: #selector(NavigationController.searchClick), for: .touchUpInside)
        return UIBarButtonItem.init(customView: searchItem)
    }
    
    /// 点击右边的搜索
    func searchClick() {
      //  let searchvc = SearchVC()
     //   self.pushViewController(searchvc, animated: true)
    }
    
    /// 返回
    func backClick() {
        self.popViewController(animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}


以上就是框架的全部,简单易懂,可以直接COPY,好爽!
还有一点,就是记得Info.plist 那个 Main storyboard 记得 delete掉哦!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,395评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,016评论 4 62
  • 今天早上儿子要返校了,早上醒过来他就眼泪汪汪的,以我对他的了解,知道他是不想去学校。所以就说“噢,你不想去学校对吧...
    minminyu阅读 322评论 11 6
  • 走过一个又一个都市 尝遍一道接一道美味 不知怎么 嘴里都觉得少了一点滋味 直到那天清晨 在街角的一处 尝到了一点鲜...
    疯不语AOA阅读 100评论 0 1
  • 学,然后知不足,比,然后见差距。不比感觉自己还好,一比感觉差距太远 。 今天上午,聆听了厦门市教育...
    幽兰盈香阅读 358评论 0 10