我正在使用 swift 版本从 Amazon SNS 向 ios 应用程序发送推送通知。 3. 当推送通知到达时,应用根据 this 切换到我设备上的第二个选项卡栏项目所以线程。 MyGlobalVariables 是在 AppDelegate.swift 中更新并在 View Controller 中读取的结构。
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
方法。
关于ios - 更新选项卡栏 View Controller 中的文本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38882822/