ios - 更新选项卡栏 View Controller 中的文本标签

标签 ios iphone swift uiviewcontroller uitabbar

我正在使用 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/

相关文章:

ios - 如何在SwiftUI分段选择器中更改选定的分段颜色

ios - 从 Web 服务器上的文本文件读取键和值的简单方法?

iphone - 从 NSData 创建 UiImage

ios - 无法使用类型为 'animateWithDuration' 的参数列表调用 '(...)'

swift - 如何在主体 View 中设置对齐方式?

ios - 获取字符串的长度

ios - UIViewController 的 navigationController 属性

ios - 为什么 Apple 的 Metal 矩阵乘法示例需要填充 C

iphone - 在运行时删除 UIImageView 中的图像背景

iphone - 从xib文件- objective-c 添加UIBarButtonItem的图像