无法将数据传输回ViewController

时间:2018-05-04 13:58:18

标签: ios swift

我在尝试将数据传回ViewController(从BarCodeScannerViewControllerTableViewController)时遇到问题

SecondVCBarCodeScannerViewController.swift):

@objc func SendDataBack(_ button:UIBarButtonItem!) {
    if let presenter = self.presentingViewController as? TableViewController {
           presenter.BarCode = "Test"
    }
    self.dismiss(animated: true, completion: nil)
}

FirstVCTableViewController.swift):

// The result is (BarCode - )
var BarCode: String = ""

override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(animated)
     print("BarCode - \(BarCode)")
}

每次运行ViewWillAppear时,都没有设置该值,可能导致此问题的原因是什么?

1 个答案:

答案 0 :(得分:4)

您应该使用委托模式。我怀疑上面的代码中self.presentingViewController实际上是设置的。

使用委托模式的示例:

// BarCodeScannerViewController.swift

protocol BarcodeScanningDelegate {
    func didScan(barcode: String)
}

class BarCodeScannerViewController: UIViewController {
    delegate: BarcodeScanningDelegate?

    @objc func SendDataBack(_ button:UIBarButtonItem!) {
        delegate?.didScan(barcode: "Test")
    }

}

// TableViewController

@IBAction func scanBarcode() {
    let vc = BarCodeScannerViewController()
    vc.delegate = self
    self.present(vc, animated: true)
}

extension TableViewController: BarcodeScanningDelegate {
    func didScan(barcode: String) {
        print("[DEBUG] - Barcode scanned: \(barcode)")
    }
}