2017-01-01 116 views
1

在我的第一個視圖控制器中,我有一個按下按鈕調用的函數。變量不在視圖控制器之間共享

func BuyButton(sender:UIButton) { 
    print("clicked cell is at row \(sender.tag)") 
    let indexPath = NSIndexPath(row: sender.tag, section: 0) 
    let currentCell = tableView.cellForRow(at: indexPath as IndexPath) as! CustomCell 
    let Storyboard = UIStoryboard(name: "Main", bundle: nil) 
    let PaymentController = Storyboard.instantiateViewController(withIdentifier: "PaymentViewController") as! PaymentViewController 
    print(currentCell.Test.text!) //prints fine here 
    PaymentController.RecordTitle = currentCell.Test.text! 
    performSegue(withIdentifier: "Buy", sender: self) 
} 

在我的付款視圖控制器我將變量定義爲

var RecordTitle = String() 

在我看來沒我的付款視圖控制器的負載我嘗試打印RecordTitle並沒有什麼打印

print(RecordTitle)//Nothing prints in payment view controller 

我究竟做錯了什麼?我已經嘗試了多種方法,但都沒有效果。

+0

更接受「SWIFTY 「** var的方式RecordTitle = String()**是** var recordTitle =」「**。駱駝案例變量和可能的推斷類型。 – dfd

回答

1

你需要重寫prepare(segue, sender)方法和該方法得到所需的視圖控制器,並設置冠軍

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "Buy" { 
     let vc = segue.destination as! PaymentViewController 
     vc.RecordTitle = sender as? String 
    } 
} 

也不要忘記調用performSegue與標題

performSegue(withIdentifier: "Buy", sender: currentCell.Test.text!) 
+0

謝謝,但我只是試過這個,但什麼也沒有 –

+0

@HaydenBowden你是否已經在'prepare'方法中指定了標題?而在'viewDidLoad'中你看到'nil'對象? –

2

你可以通過2方法更改viewController: 1:instantiateViewController 2:performSegue 但你正在結合他們 如果你想使用第一種方法只是這樣做:

func BuyButton(sender:UIButton) { 
    print("clicked cell is at row \(sender.tag)") 
    let indexPath = NSIndexPath(row: sender.tag, section: 0) 
    let currentCell = tableView.cellForRow(at: indexPath as IndexPath) as! CustomCell 
    let Storyboard = UIStoryboard(name: "Main", bundle: nil) 
    let PaymentController = Storyboard.instantiateViewController(withIdentifier: "PaymentViewController") as! PaymentViewController 
    print(currentCell.Test.text!) //prints fine here 
    PaymentController.RecordTitle = currentCell.Test.text! 
    self.presentViewController(PaymentController, animated: false, completion: nil) 
} 

,如果你有興趣在第二種方法中,有在這個環節一個很好的例子: http://www.codingexplorer.com/segue-swift-view-controllers/

+0

謝謝,這工作完美! –

相關問題