2016-11-23 56 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 
    } 

就是這樣。快樂編碼。

相關問題