当标签栏的标签/视图控制器发生变化时,如何更新标签? 迅速

问题描述

我正在开发一个带有四个独立选项卡的选项卡栏的应用程序。例如,我保存了一个可以在其中三个选项卡中更改/修改的数字。显示该数字的标签包含在所有四个选项卡中。但是,当我更改一个选项卡中的数字时,切换选项卡时其他选项卡的标签不会更新。

我尝试将其包含在选项卡的视图控制器的每个 viewDidLoad() 中:

self.tabBarController?.delegate = self 

然后使用:

func tabBarController(_ tabBarController: UITabBarController,didSelect viewController: UIViewController) {
        let tabBarIndex = tabBarController.selectedindex
        if tabBarIndex == 2{
            updateLabel()
        }
}

如果我在所有 viewController 中执行此操作并选择选项卡,视图仍​​会更改,但 tabBarController 失败,因此根本不会调用函数 updateLabel()。 如果我只在 First View Controller 中包含代码并展开这部分:

if tabBarIndex == 2{
            updateLabel()
        }

为了覆盖所有选项卡,调用了类的相应函数 (updateLabel()),但标签本身为零。

@IBOutlet weak var HoursLabel: UILabel!

func updateLabel(){
        if HoursLabel != nil{
             //code
        }    
}

而且标签没有更新。 有人知道如何解决这个问题吗?在此先感谢您:)

解决方法

嘿,我为您提供了一些解决方案,希望这就是您想要的。

我正在使用通知中心更新您的标签值,这里有一些代码

// TabbarController 代码

import UIKit

class TabbarViewController: UITabBarController,UITabBarControllerDelegate {

//MARK Life View Cycle
override func viewDidLoad() {
    super.viewDidLoad()

    tabBarController?.delegate = self
    NotificationCenter.default.addObserver(self,selector: #selector(self.TabbarNoitifuntionCall),name: NSNotification.Name(rawValue: "CallTabBarNotificationsCenter"),object: nil) // this code will call when ever you update your value in view controller
}

//MARK:- Private Functions
@objc func TabbarNoitifuntionCall(_ notification: Notification) {
    self.viewControllers![0].title = "First " + String(notification.object as! Int)
    self.viewControllers![1].title = "Second " + String(notification.object as! Int)
   }

}

// 第一个标签栏控制器

 import UIKit

 class FirstVc: UIViewController {

//MARK:- IBOutlet
@IBOutlet weak var update_lbl: UILabel!

//MARK:- Variables
var count = Int()

//MARK:- Life View Cycle
override func viewDidLoad() {
    super.viewDidLoad()
}

//MARK:- Private Function
@IBAction func buttonAction(_ sender: UIButton) {
    
    count = count + 1
    update_lbl.text = String(count)
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "CallTabBarNotificationsCenter"),object: count) // here we will call notifications center so our labal value upadate
    
   }

}

// 第二个标签栏控制器

  import UIKit

   class SecondVc: UIViewController {

//MARK:- IBOutlet
@IBOutlet weak var update_lbll: UILabel!

//MARK:- Variables
var count = Int()

//MARK:- Life View Cycle
override func viewDidLoad() {
    super.viewDidLoad()
}

//MARK:- Private Function
@IBAction func button_action(_ sender: Any) {
    count = count + 1
    update_lbll.text = String(count)
    
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "CallTabBarNotificationsCenter"),object: count) // here we will call notifications center so our labal value upadate
   }

}

我希望这是最简单的方法,如果有人添加内容,请继续 谢谢。