视图控制器之间不共享的变量

时间:2017-01-01 06:19:04

标签: ios swift

在我的第一个视图控制器中,我有一个按下按钮调用的功能。

    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

我做错了什么?我尝试了多种方法,但似乎都没有。

2 个答案:

答案 0 :(得分:2)

您可以通过2方法更改viewController: 1:instantiateViewController 2:执行塞格 但你正在将它们结合起来 如果你想使用第一种方法,就这样做:

security user

如果您对第二种方法感兴趣,可以在此链接中找到一个很好的示例: http://www.codingexplorer.com/segue-swift-view-controllers/

答案 1 :(得分: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!)