单击第一个ViewController中的button,更改第二个ViewController的标签文本
我是Swift和iOS开发新手。 我目前有2个ViewControllers
,第一个button
和第二个label
。 我已经将第一个button
连接到第二个ViewController
并且转换工作。
现在,当我尝试更改标签的文本时,出现错误:
致命错误:意外地发现零,而解包一个可选值
。
在这里,您可以在第一个ViewController
find我的准备function:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mySegue" { let vc = segue.destination as! SecondViewController vc.secondResultLabel.text = "Testing" } }
第二个ViewController
中的标签是否可以被保护?
谢谢您的帮助
您需要将String
传递给SecondViewController
而不是直接设置它,因为UILabel
尚未创build。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mySegue" { let vc = segue.destination as! SecondViewController vc.secondResultLabelText = "Testing" } }
并在你的SecondViewController
viewDidLoad
方法设置UILabel
是string
var secondResultLabelText : String! override func viewDidLoad() { secondResultLabelText.text = secondResultLabelText }
在第二个视图控制器中添加一个stringvariables
var labelText: String!
在第二个视图控制器也(在viewDidLoad)
self.secondResultLabel.text = self.labelText
那么第一个视图控制器准备继续
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mySegue" { let vc = segue.destination as! SecondViewController vc.labelText = "Testing" } }
这是因为第二个视图控制器的UILabel Outlet没有被初始化而准备继续
Rikh的答案是一样的,他的答案和我的答案是一样的
欢迎您:)
你的问题是你的SecondViewController
,更具体地说vc.secondResultLabelText
在你调用prepare
时没有启动,所以secondResultLabel
实际上是零。
你需要像这样添加一个variables到你的SecondViewController
:
var labelText: String = ""
然后设置该值,而不是:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mySegue" { let vc = segue.destination as! SecondViewController vc.labelText = "Testing" } }
在你的SecondViewController
viewWillAppear
或viewDidLoad
,你可以使用你的secondResultLabelText
这个值,它现在已经准备就绪,并且不会崩溃
secondResultLabelText.text = labelText
希望有所帮助。
首先在SecondViewController中获取一个全局variables…例如,我带了“secondViewControllerVariable”。 然后获取你想要在你的SecondViewController中显示的文本。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mySegue" { let vc = segue.destination as! SecondViewController vc.secondViewControllerVariable = "Your string you get in FirstViewController" } }
然后在你的SecondViewController中,在viewDidLoad方法中设置UILabel为string
var secondViewControllerVariable : String! // You have to declare this first in your SecondViewController Globally override func viewDidLoad() { vc.secondResultLabelText.text = secondViewControllerVariable }
而已。 快乐的编码。