2017-05-17 19 views
1

我想使用來自模態展示的其他VC中的一個rootVC的信息。下面是它的設置:無法在rootVC和模態呈現的其他VC之間傳輸信息?

protocol OtherVCDelegate { 
    func didHitOK() 
    func didHitCancel() 
} 


class ViewController: UIViewController, OtherVCDelegate { 
    func didHitCancel() { 
     //do a function 
    } 

    func didHitOK() { 
     //do another function 
    } 
    var stringy = "Hello" 

    @IBAction func ButtonAction(_ sender: Any) { 

     let otherVC = self.storyboard?.instantiateViewController(withIdentifier: "AlertVC") as! AlertVC 
     otherVC.modalPresentationStyle = .overCurrentContext 
     otherVC.delegate = self 
     otherVC.label.text = stringy //THIS is where my question focuses 
     self.present(otherVC, animated: true, completion: nil)//presents the other VC modally 

    } 

otherVC有一個名爲「標籤」的UILabel。但是,我遇到的問題是,運行ButtonAction函數時,xcode發現一個致命錯誤,因爲它在解包可選值時意外發現爲零。我有點困惑,爲什麼會發生這種情況,因爲在ButtonAction內輸入打印語句證實stringy不是零。 otherVC中的標籤正確設置,因此我不確定什麼是零值。

+1

有你試圖將該值作爲字符串傳遞,並在AlertVC中的viewDidLoad上設置標籤?我認爲在您呈現視圖控制器之前,您的標籤仍然是零。 – mat

回答

1

我不認爲你的標籤是可用的,直到你呈現你的視圖控制器。傳遞字符串,並在您的AlertVCviewDidLoad方法中設置標籤文本。

AlertVC聲明一個字符串

var stringy:String? 

那麼在這一點上更改代碼

@IBAction func ButtonAction(_ sender: Any) { 

     let otherVC = self.storyboard?.instantiateViewController(withIdentifier: "AlertVC") as! AlertVC 
     otherVC.modalPresentationStyle = .overCurrentContext 
     otherVC.delegate = self 
     otherVC.stringy = stringy //you pass the string instead of setting the label text 
     self.present(otherVC, animated: true, completion: nil)//presents the other VC modally 

    } 

可以設置在viewDidLoad文本標籤:

self.label.text = self.stringy 
+0

我會如何傳遞字符串?我熟悉使用'override func prepare(for segue:)'這樣的東西,但由於沒有真正的segue,所以VC以模態方式呈現,我如何傳遞信息? –

+0

檢查更新後的答案 – mat

相關問題