在第一个ViewController中单击按钮时更改第二个ViewController的标签文本 [英] Changing label text of second ViewController upon clicking button in first ViewController

查看:74
本文介绍了在第一个ViewController中单击按钮时更改第二个ViewController的标签文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift和iOS开发的新手。我目前在第一个和标签 ViewControllers 按钮 $ c>在第二个。我已将第一个按钮连接到第二个 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

在这里你找到我的第一个 ViewController 中的prepare函数:

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

第二个 ViewController 中的标签是否以某种方式受到保护?

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

感谢您的帮助

推荐答案

您需要将字符串传递给 SecondViewController 而不是指示设置它,因为还没有创建 UILabel

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

并在 SecondViewController viewDidLoad 方法中将 UILabel 设置为是字符串

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

var secondResultLabelText : String!

override func viewDidLoad() {

    secondResultLabelText.text = secondResultLabelText
}

这篇关于在第一个ViewController中单击按钮时更改第二个ViewController的标签文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆