Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

ios - Changing label text of second ViewController upon clicking button in first ViewController

I'm new to Swift and to iOS Development. I currently have 2 ViewControllers, a button in the first and a label in the second one. I've connected the first button to the second ViewController and the transition works.

Now, when I try changing the label's text I get the error:

fatal error: unexpectedly found nil while unwrapping an Optional value

.

Here you find my prepare function in the first ViewController:

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "mySegue" {
            let vc = segue.destination as! SecondViewController
            vc.secondResultLabel.text = "Testing"
         }
    }

Can it be that the label in the second ViewController is somehow protected ?

Thanks for the help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to pass the String to the SecondViewController instead of directing setting it, as the UILabel has not been created yet.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "mySegue" {
        let vc = segue.destination as! SecondViewController
        vc.secondResultLabelText = "Testing"
    }
}

And in your SecondViewController viewDidLoad method set the UILabel to be the string

var secondResultLabelText : String!

override func viewDidLoad() {

    secondResultLabelText.text = secondResultLabelText
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...