最近在做國際化的項(xiàng)目,踩了一下tabbarController的坑(如有知道原因的朋友望留言告知,謝謝)。
首先說說國際化的思路,項(xiàng)目需求是實(shí)現(xiàn)應(yīng)用內(nèi)切換語言,而且不銷毀棧里已有的界面,故思路如下:
1.記錄當(dāng)前選擇的語言currentLanguageCode
2.通過bundle獲取currentLanguage對(duì)應(yīng)語言的國際化文件并載入內(nèi)存
// 載入資源
let path = Bundle.main.path(forResource: currentLanguageCode, ofType: "lproj")
bundle = Bundle.init(path: path)
// 根據(jù)key獲取string
return bundle?.localizedString(forKey: key, value: alternate, table: nil)
3.切換語言以后發(fā)送通知,在需要的地方重置界面
// tabbarController:
Vc1Ref?.title = LanguageTool.getText(forKey: "key1")
Vc2Ref?.title = LanguageTool.getText(forKey: "key2")
Vc3Ref?.title = LanguageTool.getText(forKey: "key3")
Vc4Ref?.title = LanguageTool.getText(forKey: "key4")
Vc5Ref?.title = LanguageTool.getText(forKey: "key5")
那么問題來了,先看看攔截代碼
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
let nav: BaseNavigationController = viewController as! BaseNavigationController
let vc: UIViewController = nav.childViewControllers.first!
if vc.isKind(of: VC3.self) {
let vc3 = UIStoryboard.init(name: "VC", bundle: Bundle.main).instantiateViewController(withIdentifier: "VC3") as! VC3
tabBarController.present(BaseNavigationController(rootViewController: contactVc) , animated: true, completion: nil)
return false
}
return true
}
假設(shè)當(dāng)前tabbarController的selectedIndex為1,那么點(diǎn)擊vc3的時(shí)候保持當(dāng)前selectedIndex為1,并通過present彈出vc3,切換語言前一切都好好的,但是切換語言以后就變了,shouldSelect這個(gè)代理的返回值不管用了,代理仍然會(huì)走,vc3依舊會(huì)彈出,但是tabbarController中的vc3這個(gè)控制器能夠被選中了,幾經(jīng)折騰仍然無果,我猜測是UITabbarController利用item的title做了一些事情,title改變以后就出現(xiàn)了一些異常情況,當(dāng)然這個(gè)目前只是我的猜測,沒有進(jìn)行驗(yàn)證,希望指導(dǎo)原因的朋友留言告知。
最后為了滿足需求,在tabbar的代理中又做了一次攔截
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
super.tabBar(tabBar, didSelect: item)
let index = self.tabBar.items?.index(of: item)
if index == 2 {
self.selectedIndex = lastIndex
}else {
lastIndex = index!
}
}