Swift:从AppDelegate标签更新UILabel不会更新

时间:2018-07-05 22:06:23

标签: ios swift

我正在尝试从appDelegate更新UILabel,但标签从不更改文本。这是我的代码:

ViewController:

@IBOutlet weak var lblToUpdate: UILabel?

这是我的应用程序代表:

 DispatchQueue.main.async{
        let storyboard = UIStoryboard(name:"Main", bundle:nil)
        let myVC = storyboard.instantiateViewController(withIdentifier: "myVC") as! myViewController
            if let text = newText{
                myVC.text?.text = text
            }
        }

我没有任何错误,但标签从未更新。

你们中的任何人都知道为什么标签永远不会更新吗?

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

问题在于该VC

let myVC = storyboard.instantiateViewController(withIdentifier: "myVC") as! myViewController

不是显示的那个,您需要在窗口中查询它并在当前与另一个游戏一起玩时更改其标签

答案 1 :(得分:0)

由于标签时间不存在而无法工作,只需将值传递给下一个控制器中的变量,然后再传递给某些方法,例如: viewdidload ,您可以使用变量的值来更新标签,例如:

DispatchQueue.main.async{
        let storyboard = UIStoryboard(name:"Main", bundle:nil)
        let myVC = storyboard.instantiateViewController(withIdentifier: "myVC") as! myViewController
            if let text = newText{
               myVC.theVariable = text
            }
        }

class NextViewController: UIViewController {
    var theVariable = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        lblToUpdate.text = theVariable
    }

答案 2 :(得分:0)

您不应创建新实例,因为它已经存在。

您应该访问rootViewcontroller并遵循窗口层次结构

DispatchQueue.main.async{
   if let vcroot = self.window!.rootViewController {
     if let text = newText{
            vcroot.text?.text = text
      } 
   }
}

上面的代码是向您提出问题的示例。

例如,如果您有navigationcontroller:

DispatchQueue.main.async{
   if let navroot = self.window!.rootViewController as? NavigationController{
     if let childvc = navroot.childviewcontrollers.first {
         if let text = newText{
            childvc.text?.text = text
         }
     }

   }
}

如果导航控制器中有多个viewcontroller,则将使用for循环访问并检查并到达希望更改值属性或设置值的viewcontroller

相关问题