UITabBarController 总结

一. UITabBarController

  1. 在使用初始化tabBarController的过程中,如果给其set tabBarItems 时像给其setViewControllers 一样去set, (这样set viewControllers没问题,但是对于tabBarItems就有问题了)会报 'Directly modifying a tab bar managed by a tab bar controller is not allowed.'这样的错误:
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        let vc = ViewController( )
        let tabBarVC = UITabBarController()
        tabBarVC.viewControllers = [vc]
        tabBarVC.tabBar.items = [UITabBarItem(tabBarSystemItem: .contacts, tag: 0)]
        
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = tabBarVC
        window?.makeKeyAndVisible()
        return true
    }

解决办法1:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        let vc = ViewController()
        let tabBarVC = UITabBarController()
        
        tabBarVC.viewControllers = [vc]
  或者: tabBarVC.setViewControllers([vc], animated: false)
        
        for i in 0..<[vc].count {
            tabBarVC.tabBar.items?[i].image = nil
            tabBarVC.tabBar.items?[i].title = "\(i)title"
        }
        // 这样子可以实现去set tabarItem

        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = tabBarVC
        window?.makeKeyAndVisible()
        return true
    }

解决办法2:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        let vc = ViewController()
        let tabBarVC = UITabBarController()

        // 直接设置vc的tabBarItem, 其实这也是最友好最直观的一种处理方法
        vc.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 0)
        tabBarVC.setViewControllers([vc], animated: false)
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = tabBarVC
        window?.makeKeyAndVisible()
        return true
    }

遇到的坑1:

一开始做testDemo时想以最快的速度生成四个tabControllers, 于是这样写:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let vc = ViewController()
        let tabBarVC = UITabBarController()

        let vcs = [vc, vc, vc, vc]
        tabBarVC.setViewControllers(vcs, animated: false)
        
        for i in 0..<vcs.count {
            tabBarVC.tabBar.items?[i].image = nil
            tabBarVC.tabBar.items?[i].title = "\(i)title"
        }
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = tabBarVC
        window?.makeKeyAndVisible()
        return true
    }

这样看起来没有错,但跑起来会报*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]越界的错误,原因是因为vcs里虽然有四个元素[vc, vc, vc, vc], 但它们是同一个vc, 对于tabBarController来说它们是同一个,这时候tabBarController给它们创建的item就只会有一个,因此在for i in 0..<vcs.count 里,在作item?[i]时就会出现越界问题。

修改方法:

 let vc1 = ViewController()
 let vc2 = ViewController()
 let vc3 = ViewController()
 let vc4 = ViewController()
 
let vcs = [vc1, vc2, vc3, vc4]
let tabBarVC = UITabBarController()
tabBarVC.setViewControllers(vcs, animated: false)

for i in 0..<vcs.count {
    tabBarVC.tabBar.items?[i].image = nil
    tabBarVC.tabBar.items?[i].title = "\(i)title"
}        

这样创建了4个不同的vc,传到tabBarController里时才会是四个独立的vc而不会越界。

遇到的坑2:配合NavigationController使用时

想要配合导航栏使用,于是这样写:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let vc = ViewController()
        let tabBarVC = UITabBarController()
        vc.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 0)
        tabBarVC.setViewControllers([vc], animated: false)
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = UINavigationController(rootViewController: tabBarVC)
        window?.makeKeyAndVisible()
        return true
    }

看起来似乎没有什么问题,但跑起来后会发现: 即使我在ViewController里手动设置了title,但模拟器上的导航栏仍然不会显示title

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "ViewController1"
      //或者换成: navigationItem.title = "ViewController1"  亦然
        view.backgroundColor = .white
}

或者在外面创建这个navigationController时给其写上title,亦然不成功显示:

        let nav = UINavigationController(rootViewController: tabBarVC)
        nav.navigationItem.title = "444"
  //或者 nav.title = "444" 亦然
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = nav
        window?.makeKeyAndVisible()

而且这些处理方法还有可能会触发底部的tabBarItem的title变化, 比如

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let vc1 = ViewController()
        let vc2 = ViewController()
        let tabBarVC = UITabBarController()

        let vcs = [vc1, vc2]
        tabBarVC.setViewControllers(vcs, animated: false)
        
        for i in 0..<vcs.count {
            tabBarVC.tabBar.items?[i].image = nil
            tabBarVC.tabBar.items?[i].title = "\(i)title"
        }
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = UINavigationController(rootViewController: tabBarVC)
        window?.makeKeyAndVisible()
        return true
    }

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "ViewController1"
        view.backgroundColor = .white
}
tabBar1.gif

需要解决这个tabBarItem的title变化的问题可以将ViewController里的title = "ViewController1"换成navigationItem.title = "ViewController1", 但这样仍然解决不了导航栏不显示tittle的问题;

解决办法
创建相应的子控制器(viewControllers)(子视图,新建自己需要的UIViewController或者UITableViewController等等, 如果需要组合使用UINavigationController, 需要将这些视图作为UINavigationController的根视图,使用initWithRootViewController创建nav, 然后再将这些nav做成tabBarController的viewControllers)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let vc1 = ViewController()
        let vc2 = ViewController()
        let tabBarVC = UITabBarController()
        
        let nav1 = UINavigationController(rootViewController: vc1)
        let nav2 = UINavigationController(rootViewController: vc2)
        
        tabBarVC.setViewControllers([nav1, nav2], animated: false)
        
      ...
      ...
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = tabBarVC
        window?.makeKeyAndVisible()
        return true
    }

这时候在ViewController设置自己的`navigationItem.title = ""`就可以了,(注意: 不能直接self.title = "",这样会设置更新到tabBarItem的title)

假如要在外面(AppDelegate或者tabBarController去设置每一个子vc的title,)可以在创建子vc的时候: 
子vc.navigationItem.title = “vc1”...
如果有navgation, 用nav.title/nav.navigationItem.title都是不行,一定要用vc.navigationItem.title = “vc1”...才会正常显示

遇到的坑2:

在给tabBarItem设置字体或者字体颜色时遇到了给title selected 状态的字体时无效的问题。


image.png

如图,想要设置在选中状态时字体不同:

        tabBar.tintColor = .textBrand
        tabBar.unselectedItemTintColor = .textDefault
        
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.caption1], for: .normal)
        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.body], for: .selected)

理想是这样的,但发现无论怎么弄,在给selected状态设置的字体都不生效,最后找到的解决办法是在其点选的代理方法中修改:

    {
        ...
        tabBar.tintColor = .textBrand
        tabBar.unselectedItemTintColor = .textDefault
        ...
    }
    
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        tabBar.items?.forEach {
            if $0 != item {
                $0.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.caption1], for: .normal)
            }
        }
        item.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.body], for: .normal)
      //既然设置selected 状态无效,而normal有效,那么我们就都设置成normal,区分开选中与不选中来单独设置
    }

这样写完发现点选过程中可以实现预期效果了,但还有一个问题,第一次进入这个页面时默认选中第一个,且这时候并不会调用这个代理方法,这样就会使用第一次进入时第一个被选中但字体却不是我们想要的。
所以,这里还需要手动去调用一下这个方法:

//在设置tintColor处加上这句就可以了
self.tabBar(self.tabBar, didSelect: navHome.tabBarItem)

参考: iOS 设置 tabbar 选中状态字体大小

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

推荐阅读更多精彩内容