更新标签栏中的文本标签 viewcontroller

Update text label in tab bar viewcontroller

我正在从 Amazon SNS 发送推送通知到 swift 版本中的 ios 应用程序。 3. 当推送通知到达时,应用根据 this SO 线程切换到我设备上的第二个选项卡栏项目。 MyGlobalVariables 是在 AppDelegate.swift 中更新并在 viewcontroller 中读取的结构。

AppDelegate.swift

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    if let aps = userInfo["aps"] as? NSDictionary {
        if let alert = aps["alert"] as? NSDictionary {
            if let title = alert["title"] as? String {
                MyGlobalVariables.pushTitle = title
            }
            if let body = alert["body"] as? String {
                MyGlobalVariables.pushBody = body
            }
        }
    }
    if self.window!.rootViewController as? UITabBarController != nil {
        let tabbarController = self.window!.rootViewController as! UITabBarController
        tabbarController.selectedIndex = 1
    }
}

在 SecondViewController.swift 中,文本在 viewWillAppear() 中更新,一切正常。

override func viewWillAppear(_ animated: Bool) {
    pushTitleLabel?.text = MyGlobalVariables.pushTitle
}

如果我在此选项卡中时发送了具有不同标题的新推送通知,我希望在不离开和返回的情况下更新文本标签。

我试图通过将此添加到 AppDelegate.swift 来刷新文本标签。

let sVC = SecondViewController()
if let title = alert["title"] as? String {
    MyGlobalVariables.pushTitle = title
    sVC.updateLabel(t: title)
}

并且在SecondViewController.swift

中有这个功能
func updateLabel(t: String) {
    self.pushTitleLabel?.text = t
}

但我仍然需要离开选项卡并再次返回以更新文本,viewWillAppear() 负责。

问题是 let sVC = SecondViewController() 创建了 SecondViewController 新实例 ,而不是对现有实例的引用。您应该使用 tabBarController 的 viewControllers 属性 获取参考:

let sVC = tabbarController.viewControllers[1] as! SecondViewController

然后您可以调用 updateLabel 方法。