SebastianSrvn
SebastianSrvn

Reputation: 103

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.

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

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. 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.

Any ideas will be appreciated. Thank you!

Upvotes: 0

Views: 474

Answers (2)

HeliumSoft Solutions
HeliumSoft Solutions

Reputation: 11

This is easy to fix.

labelTextText is created and referenced from UI interface like as .storyboard or .xib because it has IBOutlet. So, you have to get new instance of Class AddNew via following static function.

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")
}

Upvotes: 0

chinachina123
chinachina123

Reputation: 87

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

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

Upvotes: 1

Related Questions