修改tabbarItem的title導(dǎo)致shouldSelect攔截失效

最近在做國際化的項(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!
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容