tom3377
tom3377

Reputation: 25

Changing a label in prepareforsegue

I have a issue with writing the swift code inside of the prepare for segue. I wrote code just to transfer the writing inside of my text box to a label on another view, but this crashed when I went to the other page.

var motionMovement : SecondViewController = segue.destinationViewController as SecondViewController   
motionMovement.laBel.text = teXt.text

Then I added added this to not make it crash

if segue.identifier == "hi"{
        var motionMovement : SecondViewController = segue.destinationViewController as SecondViewController
        motionMovement.laBel.text = teXt.text
    }

But now it doesn't change the label.

Upvotes: 2

Views: 1613

Answers (1)

Mustafa Ibrahim
Mustafa Ibrahim

Reputation: 1120

The outlet wasn't be allocated when you use it in prepareForSegue: .You must create a String variable in SecondViewController to store the label text in prepareForSegue: and then in the viewDidLoad in SecondViewController set it to the desired UILabel

in SecondViewController

var labelString: String?
viewDidLoad() { 
     laBel.text = labelString
}

and on prepareForSegue

if segue.identifier == "hi"{
    var motionMovement : SecondViewController = segue.destinationViewController as SecondViewController
    motionMovement.labelString = teXt.text
}

Upvotes: 4

Related Questions