无法将数据传输回视图控制器



我在尝试将数据传递回ViewController(从BarCodeScannerViewController传递到TableViewController(时遇到问题

SecondVC(BarCodeScannerViewController.swift(:

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

FirstVC(TableViewController.swift(:

// The result is (BarCode - )
var BarCode: String = ""
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("BarCode - (BarCode)")
}

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

您应该使用委托模式。我怀疑在上面的代码中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)")
}
}

最新更新