2016-11-23 26 views
1

我是Swift和iOS开发的新手。我目前有2 ViewControllers,第一个button和第二个label。我已将第一个button连接到第二个ViewController,并且转换工作正常。单击第一个ViewController中的按钮更改第二个ViewController的标签文本

现在,当我尝试改变标签的文本,我得到的错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

这里你可以找到我的第一ViewController准备功能:

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

它可以是在第二ViewController标签以某种方式保护?

感谢您的帮助

+0

看起来类似:http://stackoverflow.com/questions/39887587/error-found-nil-while-unwrapping-an-optional-value-while-pass-data-to-the-new/39887622#39887622 –

回答

4

您需要通过StringSecondViewController,而不是指导设置它,因为UILabel还没有被创建。

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

而在你SecondViewControllerviewDidLoad方法设置的UILabel为字符串

var secondResultLabelText : String! 

override func viewDidLoad() { 

    secondResultLabelText.text = secondResultLabelText 
} 
3

在第二视图控制器

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出口没有被初始化但在赛格瑞

Rikh的答案是一样的,无论是他的回答和我的准备都是一样的

2

欢迎你乘坐:)

您的问题是你的SecondViewController,更具体当您拨打prepare时不会启动,因此当时secondResultLabel实际上为零。

你需要一个变量添加到您的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" 
    } 
} 

viewWillAppearviewDidLoadSecondViewController然后你可以使用该值为您的secondResultLabelText现在已准备就绪,已连接且不会崩溃

secondResultLabelText.text = labelText 

希望有所帮助。

0

首先在SecondViewController中获取一个全局变量...例如,我拿了“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为字符串

var secondViewControllerVariable : String! // You have to declare this first in your SecondViewController Globally 

    override func viewDidLoad() 
    { 
      vc.secondResultLabelText.text = secondViewControllerVariable 
    } 

就是这样。快乐编码。

相关问题