[英]View controller changing tab bar icon and action
我正在嘗試使用我的視圖控制器類來控制選項卡欄圖像。 我想單擊一個按鈕並更改選項卡欄圖標。 Snapchat 目前在發送快照時會執行此操作。
這可能為時已晚,但對於那些路過的人,我發現了一種更簡單的方法來做到這一點。
為方便起見,請使用基類:
class BaseViewController: UIViewController {
func changeTabIcon(tab:Int){
if let tabItems = self.tabBarController?.tabBar.items {
switch tab {
case 0:
tabItems[tab].selectedImage = UIImage(named: "house_fill")
case 1:
tabItems[tab].selectedImage = UIImage(named: "folder_fill")
case 2:
tabItems[tab].selectedImage = UIImage(named: "business")
case 3:
tabItems[tab].selectedImage = UIImage(named: "cloud_fill")
default:
var _ = "something wrong"
}
}
}
然后在所有或您想要更改其圖標的 ViewControllers 中,以這種方式調用上面的方法:
class FirstViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
changeTabIcon(tab: 0)
}
}
在 SecondViewController 等中:
class SecondViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
changeTabIcon(tab: 1)
}
}
如果您在加載 ViewController 時不更改圖標,則只需調用
改變TabIcon()
在你的按鈕動作等
您可以嘗試在單擊按鈕時執行此代碼:
viewControllerToChange.tabBarItem.image = UIImage(named: "your_image_name")
例子
假設您有一個帶有 3 個視圖控制器的選項卡欄。 我們稱它們為ViewController1
、 ViewController2
和ViewController3
您想要通過單擊按鈕更改ViewController3
內部ViewController1
的選項卡欄圖標(圖像)。 在ViewController1
中,您可以使用IBAction
來處理按鈕單擊並更改ViewController3
中的選項卡欄圖標,如下所示:
@IBAction func buttonAction(_ sender: Any) {
if let viewController3 = self.tabBarController?.viewControllers?[2] {
viewController3.tabBarItem.image = UIImage(named: "your_image_name")
}
}
如果你想在同一個視圖控制器中更改標簽欄圖像,你可以簡單地將self.tabBarItem.image = UIImage(named: "your_image_name")
放在你的按鈕點擊中。
筆記
tabBarItem.image
與tabBarItem.selectedImage tabBarItem.selectedImage
。 如果在選擇選項卡時想要不同的圖像,則必須設置 selectedImage。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.