OGeek|极客世界-中国程序员成长平台

标题: ios - 更新不同 View Controller 中的标签文本 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:01
标题: ios - 更新不同 View Controller 中的标签文本

我正在努力将一个 View Controller 的选择器 View 中的选定选项传递给另一个 View Controller 中标签的标签文本。带有我要更新标签的 VC 具有 Storyboard 标识符:“PageContentViewController”。带有我的选择器 (periodPicker) 的 VC 在 View 底部有一个“选择”按钮,按下时会调用以下函数:

@IBAction func selectButtonPressed(_ sender: Any)  {

    let row = periodPicker.selectedRow(inComponent: 0)
    let selected = periodType[row]

    let pageContentViewController = self.storyboard?.instantiateViewController(withIdentifier: "ageContentViewController") as! PageContentViewController

    pageContentViewController.periodLabelTitle = selected

}

PageContentViewController类的代码是

import UIKit

class PageContentViewController: UIViewController {       

    @IBOutlet weak var periodLabel: UILabel!

    @IBOutlet weak var dateLabel: UILabel!

    var pageIndex: Int = 0
    var periodLabelTitle: String!
    var dateLabelTitle: String!

    override func viewDidLoad() {
        super.viewDidLoad()

        periodLabel.text = periodLabelTitle
        dateLabel.text = dateLabelTitle

    }

}

当通过选项卡按钮(它是一个基于选项卡的应用程序)导航到 PageContentViewController 时,标签文本不会更新。我哪里错了?

我尝试在 pageContentViewControllerviewDidAppear 方法中使用 periodLabel.text = periodLabelTitle 命令,但这仍然不起作用(在之前按下了“选择”按钮)。

我相信提到 PageContentViewControllerUIPageViewController 的子 VC 也是相关的。



Best Answer-推荐答案


selectButtonPressed(_ 中,您正在创建 PageContentViewController 的新实例:

// Creates a new instance of PageContentViewController and assigns it to pageContentViewController
let pageContentViewController = self.storyboard?.instantiateViewController(withIdentifier: "ageContentViewController") as! PageContentViewController 

要更新标签栏中可见的 View Controller 中的标签,您必须使用该实例而不是新实例。这是一个关于如何执行此操作的示例:

tabBarController?.viewControllers[0].periodLabelTitle = selected

请注意,我在示例中使用了索引 0。如果您的 PageContentViewController 不是标签栏中的第一个元素,您可能需要更改索引。

还请注意,虽然这回答了您的问题,但这可能不是实现此类事情的最佳方式,因为此解决方案取决于 View Controller 的顺序。我建议使用

关于ios - 更新不同 View Controller 中的标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316768/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4