简体   繁体   English

另一个 ViewController 中的 UILabel.text 返回 nil

[英]UILabel.text in another ViewController returns nil

I'm trying to change the text in a label in one ViewController by clicking a button in another ViewController.我试图通过单击另一个 ViewController 中的按钮来更改一个 ViewController 中 label 中的文本。

class Home: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}
var add = AddNew()

@IBAction func buttonChangeText(_ sender: Any) {
    add.printText(text: "TEXT")
}

this is the code for the first view controller这是第一个视图的代码 controller

class AddNew: UIViewController {


@IBOutlet weak var labelTextText: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    
}

func printText(text:String) {
     labelTextText?.text = text
 }

This is the code for the second vc.这是第二个vc的代码。 If I try to change it it does not do anything.如果我尝试更改它,它不会做任何事情。 I also tried printing it and it just printed nil.我也尝试打印它,它只是打印为零。 If I print or change it from the same view controller it does work.如果我从同一视图 controller 打印或更改它,它确实有效。

Any ideas will be appreciated.任何想法将不胜感激。 Thank you!谢谢!

I'm assuming you're using a segue to switch between the controllers, so first add a text property to AddNew ViewController, then change your prepareForSegue to我假设您正在使用 segue 在控制器之间切换,所以首先向 AddNew ViewController 添加一个文本属性,然后将您的 prepareForSegue 更改为

if segue.identifier == "yourSegueName" {
    let addNewVC = segue.destinationViewController as! AddNew
    AddNew?.text = "TEXT"
}

then, when you load your AddNew VC, change labelTextText to the text variable you defined earlier然后,当您加载 AddNew VC 时,将 labelTextText 更改为您之前定义的文本变量

This is easy to fix.这很容易解决。

labelTextText is created and referenced from UI interface like as.storyboard or.xib because it has IBOutlet. labelTextText是从 UI 界面创建和引用的,例如 as.storyboard 或 .xib,因为它具有 IBOutlet。 So, you have to get new instance of Class AddNew via following static function.因此,您必须通过以下 static function 获得 Class AddNew的新实例。

class AddNew: UIViewController {
    class func storyboardInstance() -> AddNew {
        let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
        return storyboard.instantiateViewController(withIdentifier: "AddNew") as! AddNew
    }
}

This is new method.这是新方法。

var add = AddNew.storyboardInstance()

@IBAction func buttonChangeText(_ sender: Any) {
    add.printText(text: "TEXT")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM