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

Categories

0 votes
913 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 Reply

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...