【问题标题】:Update text label in tab bar viewcontroller更新标签栏视图控制器中的文本标签
【发布时间】:2016-12-17 09:26:40
【问题描述】:

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

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() 负责。

【问题讨论】:

    标签: ios iphone swift uiviewcontroller uitabbar


    【解决方案1】:

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

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

    然后您可以调用updateLabel 方法。

    【讨论】:

    • 谢谢你,工作! :-) Xcode 添加了?到 viewControllers,即。视图控制器?[1]。
    猜你喜欢
    • 2021-08-09
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多